R: create new column with name coming from variable

后端 未结 2 1631
遇见更好的自我
遇见更好的自我 2021-01-11 12:50

I have a dataframe with several columns and would like to add a new column and name it according to a previous variable. For example:

df <- data.frame(\"A         


        
相关标签:
2条回答
  • 2021-01-11 13:01

    In the context of a data.frame name also taken in a variable this might be helpful.

    df <- data.frame("A" = c(1, 2, 3, 4), "B" = c("a", "c", "d", "b") )
    Variable<-"C"
    dfname<-"df"
    df<-within ( assign(dfname  , get(dfname) ),
                 assign(Variable, NA          )
               )
    
    0 讨论(0)
  • 2021-01-11 13:06

    Try [ instead of $:

    > df[, Variable] <- NA
    > df
      A B  C
    1 1 a NA
    2 2 c NA
    3 3 d NA
    4 4 b NA
    
    0 讨论(0)
提交回复
热议问题