Reputation: 257
Here is dummy data
temp.df <- data.frame(count = rep(1,6), x = c(1,1,NA,NA,3,10), y=c("A","A","A","A","B","B"))
When I apply aggregate as given below:
aggregate(count ~ x + y, data=temp.df, FUN=sum, na.rm=FALSE, na.action=na.pass)
I get:
x y count
1 1 A 2
2 3 B 1
3 10 B 1
However, I would like the following output:
x y count
1 NA A 2
2 1 A 2
3 3 B 1
4 10 B 1
Hope it makes sense.Thanks in advance.
Upvotes: 2
Views: 1326
Reputation: 886948
One option may be to convert the NA
to character "NA"
(but I am not sure why you need the missing values)
temp.df$x[is.na(temp.df$x)] <- 'NA'
aggregate(count ~ x + y, data=temp.df, FUN=sum, na.rm=FALSE, na.action=na.pass)
# x y count
#1 1 A 2
#2 NA A 2
#3 10 B 1
#4 3 B 1
Upvotes: 2
Reputation: 57686
Use addNA
to treat NA
as a distinct level of x.
> temp.df$x <- addNA(temp.df$x)
> aggregate(count ~ x + y, data=temp.df, FUN=sum, na.rm=FALSE, na.action=na.pass)
x y count
1 1 A 2
2 <NA> A 2
3 3 B 1
4 10 B 1
Upvotes: 8