R 如何从字母表向量中枚举字符串
我有以下字母向量:R 如何从字母表向量中枚举字符串,r,string,R,String,我有以下字母向量: my_alphs <- c("X","Y","Z") 我如何用R实现这一点 根据需要更改我的密码和密码 > library(dplyr) > library(stringr) > library(purrr) > do.call(expand.grid, list(rep(list(my_alphs), str_count(my_str, "\\*")), stringsAsFactors=FALSE)) %>% + accumula
my_alphs <- c("X","Y","Z")
我如何用R实现这一点 根据需要更改我的密码和密码
> library(dplyr)
> library(stringr)
> library(purrr)
> do.call(expand.grid, list(rep(list(my_alphs), str_count(my_str, "\\*")), stringsAsFactors=FALSE)) %>%
+ accumulate(function (str, replacement) str_replace(str, "\\*", replacement), .init=my_str) %>%
+ last()
[1] "LAXX" "LAYX" "LAZX" "LAXY" "LAYY" "LAZY" "LAXZ" "LAYZ" "LAZZ"
这是一个基本的R解,它可以推广到任意数量和位置的*
你如何决定哪个星号代表你的字母表中的哪个字母?或者你只是根据星号的数量使用了“my_-alphs”向量的任何可能组合?@Freakazoid所有可能的my_-alphs向量组合。@markus只是使用paste0.,LA?或者我遗漏了什么?这当然是一个选择,但我想OP会寻找一个更通用的解决方案。如果输入是*L*A*,该怎么办。
LAXX
LAXY
LAXZ
LAYX
LAYY
LAYZ
LAZX
LAZY
LAZZ
> library(dplyr)
> library(stringr)
> library(purrr)
> do.call(expand.grid, list(rep(list(my_alphs), str_count(my_str, "\\*")), stringsAsFactors=FALSE)) %>%
+ accumulate(function (str, replacement) str_replace(str, "\\*", replacement), .init=my_str) %>%
+ last()
[1] "LAXX" "LAYX" "LAZX" "LAXY" "LAYY" "LAZY" "LAXZ" "LAYZ" "LAZZ"
replace_wildcards <- function(str, alphs) {
strs <- strsplit(str, "")[[1]]
combs <- do.call(expand.grid, list(alphs)[rep(1, sum(strs == "*"))])
frame <- do.call(cbind, lapply(strs, rep, NROW(combs)))
frame[, strs == "*"] <- as.matrix(combs)
apply(frame, 1, paste, collapse = "")
}
replace_wildcards("LA**", c("X","Y","Z"))
# [1] "LAXX" "LAYX" "LAZX" "LAXY" "LAYY" "LAZY" "LAXZ" "LAYZ" "LAZZ"
replace_wildcards("*N*Y*", c("1", "2"))
# "1N1Y1" "2N1Y1" "1N2Y1" "2N2Y1" "1N1Y2" "2N1Y2" "1N2Y2" "2N2Y2"
replace_wildcards("**_is_here", c("Q", "I", "R"))
# [1] "QQ_is_here" "IQ_is_here" "RQ_is_here" "QI_is_here" "II_is_here" "RI_is_here" "QR_is_here" "IR_is_here" "RR_is_here"