Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset and replace rows and columns in a data.table

Tags:

r

data.table

I need to modify certain columns of specific rows of a data.table. I keep getting an error, "unused argument (with=F)". Does anyone know how to quickly deal with this? Below is an example using both data.frames and data.table.

Thanks.

     test.df <- data.frame(a=rnorm(100, 0, 1), b=rnorm(100, 0, 1), c=rnorm(100,0,1))
     test.dt <- as.data.table(test.df)

     test.df[test.df$a<test.df$b,c(1,2)] <- 10* test.df[test.df$a<test.df$b,c(1,2)]

     test.dt[test.dt$a<test.dt$b, c(1,2), with=F] <- 10* test.dt[,c(1,2),with=F][test.dt$a<test.dt$b, c(1,2), with=F]
like image 633
Alan Avatar asked Feb 12 '23 22:02

Alan


1 Answers

First of all - you do not need to, and should not (as a matter of good programming) use the data.table name inside [.data.table.

Secondly, you should avoid using column numbers whenever you can - this is a source of future headache, and should instead aim to use column names.

Finally, the way to change columns in data.table's is to use the := operator to modify in-place (see ?':=').

Combining all of the above, this is what you should do:

test.dt[a < b, `:=`(a = 10 * a, b = 10 * b)]
like image 144
eddi Avatar answered Feb 19 '23 01:02

eddi