[R] data.table - How do I transform a set of column?

arun smartpink111 at yahoo.com
Mon Mar 17 15:42:08 CET 2014


Hi,
May be this helps:
dt1 <- copy(dt)

 dt[,c("b","c"):=lapply(.SD,function(x) x^2),.SDcols=2:3]

#or

 for(.col in 2:3) set(dt1,j=.col,value=dt1[[.col]]^2)


identical(dt,dt1)
#[1] TRUE
A.K.




On Monday, March 17, 2014 10:27 AM, Witold E Wolski <wewolski at gmail.com> wrote:
I started to use the data.table to subset, reshape large data.
But how do I transform a set of columns?

# for a data.frame I would do:

df = data.frame(a = c("a","b","c","d"), b = 1:4,c = 1:4)
df[,2:3] = df[,2:3]^2


# but with data.table this somehow similar code produces an error.

dt = data.table(a = c("a","b","c","d"), b = 1:4,c = 1:4)
dt[, 2:3 , with=FALSE ] = x[,2:3,with=FALSE]^2


By the way.

I need the columns selection 2:3 because column 1 in data.table
contains the keys.
With data.frame, matrix I would store the keys as rownames.
and just write:
df = df^2
(easier to read)


Is there syntactic sugar in data.table to be able to say something like:
transform all nonkey columns, replace all nonkey columns?


best regards
Witold









-- 
Witold Eryk Wolski

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.





More information about the R-help mailing list