在 R 中,如何用返回可能输出向量的歧义的所有选项替换字符串中的歧义字符?
In R, How can I replace ambiguous characters in string with all options for the ambiguity returning a vector of possible outputs?
这是我要解决的问题。
#Original String
#Where ! is a ambiguous character which represent 2:n different characters. Here i assume it stands for either "1" or "2".
I also have multiple ambiguity characters e.g. "?" = "3" or "4".
"A!!C!!D?"
#I want to know all forms a disambiguated string could take.
I.e, in this case .!!.!!.? could produce
4*4*2 = 32 possibilities.
#I want a function to return all possibilities as a vector.
#e.g. desired return
c("A11C11D3", "A11C12D3", "A11C21D3", "A11C22D3",
"A12C11D3", "A12C12D3", "A12C21D3", "A12C22D3",
...
)
我是否缺少一个简单的函数来执行此操作,或者我是否需要使用 gsub 或类似工具从头开始构建它。
一种方法是拆分字符串,用可能的值替换不明确的字符,生成可能的组合并粘贴回去。
mystring <- "A!!C!!D?"
lapply(strsplit(mystring, ""), function(x) {
res <- lapply(x, function(y)
switch(y,
"!" = 1:2,
"?" = 3:4,
y)
)
do.call(paste0, expand.grid(res))
})
[[1]]
[1] "A11C11D3" "A21C11D3" "A12C11D3" "A22C11D3" "A11C21D3" "A21C21D3" "A12C21D3" "A22C21D3" "A11C12D3" "A21C12D3" "A12C12D3" "A22C12D3"
[13] "A11C22D3" "A21C22D3" "A12C22D3" "A22C22D3" "A11C11D4" "A21C11D4" "A12C11D4" "A22C11D4" "A11C21D4" "A21C21D4" "A12C21D4" "A22C21D4"
[25] "A11C12D4" "A21C12D4" "A12C12D4" "A22C12D4" "A11C22D4" "A21C22D4" "A12C22D4" "A22C22D4"
这是我要解决的问题。
#Original String
#Where ! is a ambiguous character which represent 2:n different characters. Here i assume it stands for either "1" or "2".
I also have multiple ambiguity characters e.g. "?" = "3" or "4".
"A!!C!!D?"
#I want to know all forms a disambiguated string could take.
I.e, in this case .!!.!!.? could produce
4*4*2 = 32 possibilities.
#I want a function to return all possibilities as a vector.
#e.g. desired return
c("A11C11D3", "A11C12D3", "A11C21D3", "A11C22D3",
"A12C11D3", "A12C12D3", "A12C21D3", "A12C22D3",
...
)
我是否缺少一个简单的函数来执行此操作,或者我是否需要使用 gsub 或类似工具从头开始构建它。
一种方法是拆分字符串,用可能的值替换不明确的字符,生成可能的组合并粘贴回去。
mystring <- "A!!C!!D?"
lapply(strsplit(mystring, ""), function(x) {
res <- lapply(x, function(y)
switch(y,
"!" = 1:2,
"?" = 3:4,
y)
)
do.call(paste0, expand.grid(res))
})
[[1]]
[1] "A11C11D3" "A21C11D3" "A12C11D3" "A22C11D3" "A11C21D3" "A21C21D3" "A12C21D3" "A22C21D3" "A11C12D3" "A21C12D3" "A12C12D3" "A22C12D3"
[13] "A11C22D3" "A21C22D3" "A12C22D3" "A22C22D3" "A11C11D4" "A21C11D4" "A12C11D4" "A22C11D4" "A11C21D4" "A21C21D4" "A12C21D4" "A22C21D4"
[25] "A11C12D4" "A21C12D4" "A12C12D4" "A22C12D4" "A11C22D4" "A21C22D4" "A12C22D4" "A22C22D4"