Hao Hao - 1 month ago 17
R Question

Aggregate by NA value in R

x1 <- c(1, 2, 3)
x2 <- c("a", "b", "a")
x3 <- as.Date(c(NA, "2016/01/01", NA), "%Y/%m/%d")
df <- data.frame(x1,x2,x3)


when I apply aggregate to
df
:

aggregate(x1~x2+x3, df, sum)


The result looks like this but ignored
NA
values:

x2 x3 x1
b 2016/01/01 2


So what I need is to aggregate
NA
values and have a result like this:

x2 x3 x1
a NA 4
b 2016/01/01 2


Can anyone please help on this?

Answer

I accomplished this by adding NA as a factor level then performing the aggregation:

x1 <- c(1, 2, 3)
x2 <- c("a", "b", "a")
x3 <- as.factor(as.Date(c(NA, "2016/01/01", NA), "%Y/%m/%d"))
x3 <- addNA(x3)
df <- data.frame(x1,x2,x3)

aggregate(x1~x2+x3, df, sum)
  x2         x3 x1
1  b 2016-01-01  2
2  a       <NA>  4