简体   繁体   English

根据 data.table 中的某些匹配替换列的某些值

[英]Replacing some values of a column based on some match in data.table

Let say I have below data.table假设我有以下 data.table

library(data.table)
DT = data.table(Col1 = LETTERS[1:10], Col2 = c(1,4,2,3,6,NA,4,2, 5, 4))
DT 

    Col1 Col2
 1:    A    1
 2:    B    4
 3:    C    2
 4:    D    3
 5:    E    6
 6:    F   NA
 7:    G    4
 8:    H    2
 9:    I    5
10:    J    4

Now I want to replace the 4 and NA values in Col2 by 999现在我想用999替换Col2中的4 and NA

In actual scenario, I have very large DT , so I am looking for most efficient way to achieve the same.在实际场景中,我有非常大的DT ,所以我正在寻找最有效的方法来实现同样的目标。

Any insight will be highly appreciated.任何见解都将受到高度赞赏。

An option with na_if/replace_na带有na_if/replace_na的选项

library(dplyr)
library(data.table)
DT[, Col2 := replace_na(na_if(Col2, 4), 999)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM