loop for character variable names in r

后端 未结 2 1207
余生分开走
余生分开走 2021-01-26 04:21

I have a list of variables, like a1, a2, a3. Then I want to do a loop for these variable, for instance, assign values. I tried paste, which just gave character like \"a1\", that

2条回答
  •  一向
    一向 (楼主)
    2021-01-26 05:22

    The loop assigns values to all elements in your object. 'a1' gets value '2'; 'a2' gets value '3'; etcetera.

    library(stringr)
    val <- str_c("a", 1:3)
    
    for (i in 1:length(val)){
      assign(val[i], i+1)
    }
    get(val[1])#2
    get(val[2])#3
    get(val[3])#4
    

提交回复
热议问题