[英]Assign values to multiple columns on subset using “:=” from data.table
Following up on this question, how would you assign values to multiple columns in a data table using the ":=" sign? 跟进这个问题,如何使用“:=”符号将值分配给数据表中的多个列?
For example: 例如:
x <- data.table(a = 1:3, b = 1:6, c = 11:16)
I can get what i want using two lines: 我可以使用两行代码得到我想要的:
x[a>2, b:=NA]
x[a>2, c:=NA]
but would like to be able to do it in one, something like this: 但希望能够做到这一点,就像这样:
x[a>2, .(b:=NA, c:=NA)]
But unfortunately that doesn't work. 但不幸的是,这行不通。 Is there another way? 还有另一种方法吗?
We can use the :=
once with 我们可以使用:=
一次
x[a >2, `:=`(b = NA, c = NA)]
If there are many columns, another option is set
如果列很多,则set
另一个选项
for(nm in names(x)[-1]) set(x, i=which(x[["a"]]>2), j=nm, value = NA)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.