Alan
Alan

Reputation: 41

Subset and replace rows and columns in a 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]

Upvotes: 4

Views: 3633

Answers (1)

eddi
eddi

Reputation: 49448

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)]

Upvotes: 8

Related Questions