afrendeiro
afrendeiro

Reputation: 2544

R: generate combinations of strings between groups

In bash one can easily generate combinations of strings between groups such as this:

> 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?

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!

Upvotes: 1

Views: 86

Answers (2)

afrendeiro
afrendeiro

Reputation: 2544

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"

Upvotes: 1

Se&#241;or O
Se&#241;or O

Reputation: 17412

outer is usually the right function when you're trying to combine combinations.

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"

Upvotes: 1

Related Questions