I would like to use a variable to specify the name of a column when operating on it.
To give an example I can might have a data.table called Set1 in which I want to change the class of column x to numeric. I might do
Set1New=transform(Set1,x=as.numeric(x))
This will work, but now I don't want to hard code the column name, but rather use a variable, lets's call it Y (which has previously been defined as Y="x".
How do I tell R to use the content of the variable instead of looking for a column Y when I use
Set1New=transform(Set1,Y=as.numeric(Y))
I know that e.g. setkey and setkeyv exist, where setkeyv solves this issue. Is there a similar solution for transform? Or, what I would like better, is there a general solution to use the content of the variable instead of the variable name?
Data:
library(data.table)
dt = data.table(col1=letters[1:2], x=c('1','2'))
One solution is to use quote and the eval in your data.table:
y = quote(x)
dt[,eval(y):=as.numeric(eval(y))]
#> is.numeric(dt$x)
#[1] TRUE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With