在R中,如何将列分配给数据框并使用变量名?

4

使用变量名将值赋给数据帧的列。

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

什么问题?这对我来说似乎是有效的。 - Dason
好的,你看看这个...它们都能工作...我想知道发生了什么。 - Skylar Saveland
1个回答

7
语法是:
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

哇,非常棒的答案,但我还缺少其他东西。貌似 dframe[, destination_string] <- mynewcolumn 也可以行得通。 - Skylar Saveland
请查看 R-FAQ:http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f - IRTFM
这似乎只在dframe不为空(必须至少有一列)时有效。尝试 dframe <- data.frame(); df[["foo"]] <- 1:4,你将会得到一个错误信息:“Error in '[[<-.data.frame'('tmp', "foo", value = 1:4) : replacement has 4 rows, data has 0”。 这在R版本4.1.2中出现。 如果您想通过循环逐列构建数据框,这可能会成为一个问题。是的,有时候您需要这样做,即使这不符合R的思维方式。 - András Aszódi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接