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

编程入门 行业动态 更新时间:2024-10-08 03:45:33
本文介绍了有条件地用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:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616613.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   data   table

发布评论

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

>www.elefans.com

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