Variable as a column name in data frame

前端 未结 3 1768
无人共我
无人共我 2021-02-06 23:07

Is there any way to use string stored in variable as a column name in a new data frame? The expected result should be:

col.name <- \'col1\'
df <- data.fram         


        
3条回答
  •  Happy的楠姐
    2021-02-06 23:38

    In addition to ssdecontrol's answer, there is a second option.

    You're looking for mget. First assign the name to the variable, then the value to the variable that you have previously assigned. After that, mget will evaluate the string and pass it to data.frame.

    assign(col.name, "col1")
    assign(paste(col.name), 1:4)
    
    df <- data.frame(mget(col.name))
    print(df)
      col1
    1    1
    2    2
    3    3
    4    4
    

提交回复
热议问题