Bogaso
Bogaso

Reputation: 3308

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

Let say I have below 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

In actual scenario, I have very large DT, so I am looking for most efficient way to achieve the same.

Any insight will be highly appreciated.

Upvotes: 0

Views: 31

Answers (1)

akrun
akrun

Reputation: 886938

An option with na_if/replace_na

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

Upvotes: 1

Related Questions