Home > front end >  Programmatically create a named vector with for loops
Programmatically create a named vector with for loops

Time:06-08

I'm trying to create a named vector where the names change according to the variable of a loop or a map. Something like this:

for (i in 1:5) { 
  named_vector <- c(
    str_c("variable_A_", i) = i,
    str_c("variable_B_", i) = i,
    str_c("variable_C_", i) = i
  ) 
}


but I get the following error:

Error: unexpected '=' in:
"  named_vector <- c(
    str_c("variable_A_", i) ="

I know you can use the assign() function:

for (i in 1:5) { 
  named_vector <- c(
    assign(str_c("variable_A_", i), i),
    assign(str_c("variable_B_", i), i),
    assign(str_c("variable_C_", i), i)
  ) 
}

But if I do that I lose the name attribute, which I really need to do a mutate(data, recode(column, !!!named_vector)) later on.

Thanks

CodePudding user response:

Do you need something like this ?

named_vector <- setNames(rep(1:5, each = 3), 
                    paste0('variable_', 
                      outer(c('A', 'B', 'C'), 1:5, paste, sep = '_')))
named_vector

#variable_A_1 variable_B_1 variable_C_1 variable_A_2 variable_B_2 variable_C_2 
#           1            1            1            2            2            2
 
#variable_A_3 variable_B_3 variable_C_3 variable_A_4 variable_B_4 variable_C_4 
#           3            3            3            4            4            4
 
#variable_A_5 variable_B_5 variable_C_5 
#           5            5            5 
  • Related