在 R data.table 中,添加一个名称基于字符串的列

han*_*ick 3 string r function data.table

我想向 data.table 添加一列。但是这个新列的名称必须从字符向量中提取。我这样写:

add_var=function(index){
  label=c("products","price")
  var_name=label[index]
  df=data.frame(x=c(1,2,5,9),y=c(5,2,6,7))
  dt=as.data.table(df)
  dt[,(as.name(var_name)):=5]
  return(dt)
}
new_ds=add_var(1)
Run Code Online (Sandbox Code Playgroud)

我期待这样的事情

x y products
1 5        5
2 2        5
5 6        5
9 7        5
Run Code Online (Sandbox Code Playgroud)

但是,相反,我收到了此错误消息:

 Error in `[.data.table`(dt, , `:=`((as.name(var_name)), 5)) : 
  LHS of := must be a symbol, or an atomic vector (column names or positions). 
Run Code Online (Sandbox Code Playgroud)

任何人都知道如何修复我的功能以使其正常工作?

raf*_*ira 5

你只需要这个:

label <- c("products","price")
df <- data.frame(x=c(1,2,5,9),y=c(5,2,6,7))


setDT(df)[ , (label) := 5]


#>    x y label products price
#> 1: 1 5     5        5     5
#> 2: 2 2     5        5     5
#> 3: 5 6     5        5     5
#> 4: 9 7     5        5     5
Run Code Online (Sandbox Code Playgroud)

  • `setDT(df)` 将 `data.frame` 转换为 `data.table`,而不将其复制到内存中。你也可以分两个单独的步骤来完成,首先是`setDT(df)`,然后是`df[, (label) := 5]`。如果你想把它转换回一个 `data.frame`,它就像 `setDF(df)` 一样简单 (3认同)