R将列分配给具有变量名称的数据框

标签 r syntax

使用变量名称分配给数据框列。

getModified <- function(dframe, destination_string, foo, bar) {
    # complex calculations on foo and bar getting mynewcol here
    # ...

    # I want to add mynewcolumn with name in destination_string
    # if "blah" was the destination_string, the result would be as:
    #dframe$blah <- mynewcol
    #return(dframe)

    # what is the syntax for using the variable?
    # no luck here:
    dframe[, destination_string] <- mynewcolumn
    return(dframe)
  }

这样我就可以打电话

dframe <- getModified(dframe, "nameofmynewcolum", foo, bar)
dframe$nameofmynewcolumn

最佳答案

语法是

dframe[[destination_string]] <- mynewcolumn

例如,

getModified <- function(dframe, destination_string, foo) {
  dframe[[destination_string]] <- foo
  dframe
}
>     getModified(data.frame(A=1:10), "newColName", 11:20)
    A newColName
1   1         11
2   2         12
3   3         13
4   4         14
5   5         15
6   6         16
7   7         17
8   8         18
9   9         19
10 10         20

关于R将列分配给具有变量名称的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12015481/

相关文章:

r - 2 条曲线之间的阴影区域

javascript - 无法使用 Javascript 呈现 XML

c - 在 while 循环中与乘法一起使用的后递增

linux - 整数表达式预期的sqlplus

regex - R gsub 从文本中提取电子邮件

r - ggplot2: annotation_custom 给出一个空层

R,对具有重复条目的连续行的数据帧进行操作

c++ - typedef T Type::* 语法

html - HTML5 语法中的 "Text"是否表示 "any character"?

r - 如何计算 15 年 31 天的每日平均值,并考虑缺失值?