Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R data.table, add a column which name is based on a string

I want to add a column to a data.table. But the name of this new column have to be extract from a character vector. I write this :

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)

And I expected something like

x y products
1 5        5
2 2        5
5 6        5
9 7        5

But, instead, I got this error message :

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

Anyone know how to fix my function to make it work?

like image 352
hans glick Avatar asked Nov 15 '25 01:11

hans glick


1 Answers

You just need this:

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
like image 86
rafa.pereira Avatar answered Nov 17 '25 17:11

rafa.pereira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!