R:创建新列,名称来自变量 [英] R: create new column with name coming from variable
本文介绍了R:创建新列,名称来自变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含几列的数据框,并想添加一个新列并根据以前的变量将其命名。例如:
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" = c(1, 2, 3, 4), "B" = c("a", "c", "d", "b"))
Variable <- "C"
这是函数的一部分,变量将在其中更改,而不是每次都指定:
This is part of a function where the variable will be changing and rather than each time specifying:
df$C <- NA
我想一行以变量命名为附加列
I would like a one line that will take the "Variable" to name the additional column
推荐答案
尝试 [
而不是 $
:
> df[, Variable] <- NA
> df
A B C
1 1 a NA
2 2 c NA
3 3 d NA
4 4 b NA
这篇关于R:创建新列,名称来自变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文