Fabio Correa
Fabio Correa

Reputation: 1363

Unexpected behavior of data.table := when subsetting

Given the data.table dt <- data.table(a=c(1,NA,3), b = c(4:6))

    a b
1:  1 4
2: NA 5
3:  3 6

... , the result for dt[is.na(a), a := sum(a, na.rm = T)] is:

   a b
1: 1 4
2: 0 5
3: 3 6

... , instead of the expected:

   a b
1: 1 4
2: 4 5
3: 3 6

What is going on? I am using data.table 1.12.8

Upvotes: 1

Views: 47

Answers (1)

akrun
akrun

Reputation: 887088

We could use fcoalesce

library(data.table)
dt[, a := fcoalesce(a, sum(a, na.rm = TRUE))]

Upvotes: 1

Related Questions