I need to create variable names based on permutations of a couple of levels. I do not want to use a loop to do it though. Here is some example code,
Varname <- "Var"
Level1 <- c("A","B")
Level2 <- c(1,2,3)
If I write this I get a the first level.
> paste0(Varname , Level1)
[1] "VarA" "VarB"
I would like to a method to get either of these results
"VarA1" "VarA2" "VarA3" "VarB1" "VarB2" "VarB3"
"VarA1" "VarB1" "VarA2" "VarB2" "VarA3" "VarB3"
I thought this would work but alas no
> paste0( paste0(Varname , Level1) , Level2)
[1] "VarA1" "VarB2" "VarA3"
Is there a way to do this simply or a function that does this, without having to use a loop. Thanks in advance.
CodePudding user response:
We can use outer
to apply a function to all combinations of 2 variables:
paste0(Varname, outer(l1, l2, paste0))
# [1] "VarA1" "VarB1" "VarA2" "VarB2" "VarA3" "VarB3"
CodePudding user response:
Using expand.grid
and paste0
you could do:
d <- expand.grid(Level2, Level1)
paste0(Varname, d$Var2, d$Var1)
#> [1] "VarA1" "VarA2" "VarA3" "VarB1" "VarB2" "VarB3"