问题描述
我有以下data.table:
I have the following data.table:
dt <- data.table(col1 = rep("a",6), col2 = c(1,1,1,2,3,1))
现在,我想用值 bigDog替换col2中的所有1。我可以使用data.frame的精神实现它:
Now I want to replace all the 1 in col2 with value "bigDog". I can do it using the data.frame spirit:
dt$col2[dt$col2==1,] <- "bigDog"
但是我想知道是否还有其他方法,更多的 data.table ?
But I wonder if there is a different way, more "data.table oriented"?
推荐答案
如果您不想更改列的类型,可以这样做:
Had you not wanted to change the type of the column, you'd do:
dt[col2 == 1, col2 := 123]
更改类型后,您可以执行以下操作:
With the type change, you can do:
dt[, col2 := as.character(col2)][col2 == "1", col2 := "bigDog"]
如果您不首先更改类型,则 bigDog将被强制转换为整数,即 NA
。当然,您还会收到很多警告。
If you don't change the type first, "bigDog" will get coerced to integer, i.e. NA
. You'll also get a bunch of warnings about that of course.
请注意,除了语法比较简单之外,还使用:=
的优点是不制作额外的数据副本(如<-
那样),而是就地进行修改。
Note that besides less cumbersome syntax, using :=
has the advantage of not making extra copies of data (as <-
will) and instead modifies in place.
这篇关于有条件地用data.table替换列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!