从R中的字符串绑定动态列名

Rah*_*hul 3 r dataframe

我想使用从字符串动态分配的列名将列绑定到数据框

y_attribute = "Survived"
cbind(test_data, y_attribute = NA)
Run Code Online (Sandbox Code Playgroud)

这会导致添加新列,y_attribute而不是必需Survived属性,该属性作为字符串提供给y_attribute变量。要使用从变量提供的列名来获取数据框中的列,需要做些什么?

akr*_*run 5

我们可以用它tidyverse来做到这一点

library(dplyr)
test_data %>%
     mutate(!! y_attribute := NA)
#   col1 Survived
#1    1       NA
#2    2       NA
#3    3       NA
#4    4       NA
#5    5       NA
Run Code Online (Sandbox Code Playgroud)

数据

test_data <- data.frame(col1 = 1:5)
Run Code Online (Sandbox Code Playgroud)


Gre*_*gor 5

您实际上不需要cbind添加新列。以下任何一项均可使用:

test_data[, y_attribute] = NA # data frame row,column syntax
test_data[y_attribute] = NA   # list syntax (would work for multiple columns at once)
test_data[[y_attribute]] = NA # list single item syntax (single column only)
Run Code Online (Sandbox Code Playgroud)

就像一样,新列会添加到现有列之后cbind

  • 您可以执行类似rbind(train_data,{test_data [,y_attribute] = NA})的操作将其强制为一行,但我不建议这样做。 (2认同)