Reputation: 1
I would like to add multiple columns to a data.table depending on the values in other columns, in one function, e.g.
d.f <- data.frame(a=c(1,2,3),b=c(4,5,1))
d.t <- data.table (d.f)
g <- function(x,y){
if (y>x)
return (list(1,2))
else
return (list(2,1))
}
d.t[,c('x','y'):=g(a,b)]
But this errors out, and using ifelse doesn't seem to work either.
Upvotes: 0
Views: 575
Reputation: 22333
You should use ifelse
instead of if (...)
else
. Also the return statement should be a list of length 2, with each list element having the same length as x
and y
.
g <- function(x,y){
list(ifelse(y>x, 1, 2),
ifelse(y>x, 2, 1))
}
Upvotes: 4