0

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?

Community
  • 1
  • 1
Jakob
  • 1,325
  • 15
  • 31
  • As the message says, y is integer. As a safety measure, it doesn't let you overwrite a variable with a new type when working by group. You can do a first step of `test[, (cols) := lapply(.SD, as.numeric), .SDcols=cols]` before doing the rescaling. – Frank Apr 04 '17 at 15:39
  • This is because your original column have different class. Change it to the required class before assigning – akrun Apr 04 '17 at 15:40
  • right, thanks. I'll leave the question as a pointer – Jakob Apr 04 '17 at 17:12

0 Answers0