有条件地用 data.table 替换列值

编程入门 行业动态 更新时间:2024-10-08 05:26:10
本文介绍了有条件地用 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 替换列值

本文发布于:2023-11-22 08:06:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616612.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   data   table

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!