Hao - 1 year ago 73

R Question

`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`

`x2 x3 x1`

b 2016/01/01 2

So what I need is to aggregate

`NA`

`x2 x3 x1`

a NA 4

b 2016/01/01 2

Can anyone please help on this?

Answer Source

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`