[英]R: generate combinations of strings between groups
In bash one can easily generate combinations of strings between groups such as this: 在bash中,可以轻松地在组之间生成字符串组合,例如:
> echo {'A','B'}_{'1','2'}_S_R
A_1_S_R A_2_S_R B_1_S_R B_2_S_R
Does anyone know how to generate such combinations of strings in R? 有谁知道如何在R中生成这样的字符串组合?
I have tried the following but it seems to only repeat the first elements and not the seconds. 我已经尝试了以下内容,但似乎只重复了第一个元素,而不是秒。
paste(rep(c("A", "B"), 2), c("1", "2"), "S", "R", sep = "_")
[1] "A_1_S_R" "B_2_S_R" "A_1_S_R" "B_2_S_R"
paste(rep(c("A", "B"), 2), rep(c("1", "2"), 2), "S", "R", sep = "_")
[1] "A_1_S_R" "B_2_S_R" "A_1_S_R" "B_2_S_R"
Thank you! 谢谢!
outer
is usually the right function when you're trying to combine combinations. 当您尝试组合组合时,
outer
通常是正确的功能。
paste(outer(LETTERS[1:2], 1:2, paste, sep="_"), "_S_R", sep="")
[1] "A_1_S_R" "B_1_S_R" "A_2_S_R" "B_2_S_R"
Ok, I've figured a way, but it doesn't seem too obvious/efficient. 好的,我找到了一种方法,但是它似乎不太明显/效率很高。
Please add your answer if you find a better way. 如果您找到更好的方法,请添加您的答案。
> df<-expand.grid(c("A", "B"), c("1", "2"), "S", "R")
> paste(df[,1],df[,2], df[,3],df[,4],sep="_")
[1] "A_1_S_R" "B_1_S_R" "A_2_S_R" "B_2_S_R"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.