I'm trying to do a within transformation (variable-mean(variable)) over my dataset but by id category. I get a common error
Type of RHS ('double') must match LHS ('integer').
that I never really understand. Somehow data.table can't assign the new variable to the old one because of different types? But everything is numeric... Example:
test <- data.table(id=rep(1:10,each=20),time=rep(1991:2010,10),
y=rbinom(200,1,0.1),
x1=rnorm(200,mean=5,sd=2),
x2=rnorm(200),
x3=rbeta(200,shape1=1,shape2=2))
cols <- c("y","x1","x2","x3")
test[ , (cols) := lapply(.SD, function(x){x-mean(x,na.rm=T)}), .SDcols = cols,by=id]
This code was adapted from this question and it works fine if you delete the by=id
argument. What am I missing?