简体   繁体   English

子集并替换data.table中的行和列

[英]Subset and replace rows and columns in a data.table

I need to modify certain columns of specific rows of a data.table. 我需要修改data.table的特定行的某些列。 I keep getting an error, "unused argument (with=F)". 我不断收到错误,“未使用的参数(带= F)”。 Does anyone know how to quickly deal with this? 有谁知道如何快速处理这个? Below is an example using both data.frames and data.table. 下面是使用data.frames和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]

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 . 首先 - 你不需要,也不应该(作为一个好的编程问题)在[.data.table使用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 ?':=' ). 最后,更改data.table列的方法是使用:=运算符进行就地修改(参见?':=' )。

Combining all of the above, this is what you should do: 结合以上所有,这是你应该做的:

test.dt[a < b, `:=`(a = 10 * a, b = 10 * b)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM