从R中的字符串绑定动态列名 [英] cbind a dynamic column name from a string in R
本文介绍了从R中的字符串绑定动态列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用从字符串动态分配的列名将列绑定到数据框
I want to cbind a column to the data frame with the column name dynamically assigned from a string
y_attribute = "Survived"
cbind(test_data, y_attribute = NA)
这会导致新列添加为 y_attribute
而不是必需的 Survived
属性,该属性作为字符串提供给y_attribute变量。要使用从变量提供的列名来获取数据框中的列,需要做些什么?
this results in a new column added as y_attribute
instead of the required Survived
attribute which in provided as a string to the y_attribute variable. What needs to be done to get a column in the data frame with the column name provided from a variable?
推荐答案
我们可以使用 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
数据
data
test_data <- data.frame(col1 = 1:5)
这篇关于从R中的字符串绑定动态列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文