r - Access data.table columns with strings -


apologies question makes obvious work in python/pandas, i'm stuck this. how select data.table column using string?

dt$"string" dt$as.name("string") dt$get("string") 

i'm sure super simple, i'm not getting it. appreciated!


-------------- edited add ----------------------

after of helpful comments , tips below, think i've narrowed down problem bit , have reproducible example. consider:

dt = data.table(id = c("a","a","a","b","b","b"), col1=rnorm(6), col2=rnorm(6)*100) 

and assume want assign values in col2 col1. i've learned below, data.table syntax dt[,col1:=col2], clean , simple. problems start when 1 (or both) of variables in j argument strings. found following:

dt[, "col1":=col2] works expected

dt[, "col1":="col2"] fails expected (tries assign character col2 double vector col1

dt[, "col1":=get("col2")] works expected

dt[, get("col1")] returns col1 expected

but: dt[, get("col1"):=col2] or other assignment fails.

some context: reason doing i'm constructing strings in loop, access larger number of columns named colname_colnumber, i.e. loop on colname , colnumber access column paste0(colname,colnumber).

you can use get() j argument using single brackets:

library(data.table) dt <- data.table(iris) dt[, get("species")] 

the result:

[1] setosa     setosa     setosa     setosa     setosa     setosa ..... 

you can use string directly inside double bracket operator, this:

dt[["species"]] 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -