有条件地用 data.table 替换列值 [英] Conditionally replacing column values with data.table
问题描述
我有以下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 替换列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!