【问题标题】:R assign column to dataframe with variable nameR将列分配给具有变量名称的数据框
【发布时间】:2012-08-14 11:22:41
【问题描述】:

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

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

【问题讨论】:

  • 到底是什么问题?这似乎对我有用。
  • 好吧,你看一下...他们都工作...我想知道发生了什么。

标签: r syntax


【解决方案1】:

语法是

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] &lt;- mynewcolumn 似乎也有效。
  • 请查看 R-FAQ:cran.r-project.org/doc/FAQ/…
猜你喜欢
  • 2021-08-03
  • 2018-12-26
  • 2018-10-16
  • 2018-10-21
  • 2014-11-03
  • 1970-01-01
  • 1970-01-01
  • 2012-11-04
  • 2019-01-11
相关资源
最近更新 更多