Aggregate by NA in R

后端 未结 5 1874
闹比i
闹比i 2021-01-13 11:22

Does anybody know how to aggregate by NA in R.

If you take the example below

a <- matrix(1,5,2)
a[1:2,2] <- NA
a[3:5,2] <- 2
aggregate(a[,1]         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-13 12:01

    You can also try aggregating by is.na(a[,2]) instead.

    aggregate(a[,1], by=list(is.na(a[,2])), sum)
    
    #   Group.1 x
    # 1   FALSE 3
    # 2    TRUE 2
    

    If you want a finer distinction than just NA or not, then you may want to define a new variable that uses an previously unused value to denote NA (a factor would be more elegant, but a numeric vector is the simplest):

    b <- a[,2]
    b[is.na(b)] <- 999
    aggregate(a[,1], by=list(b), sum)
    
    #   Group.1 x
    # 1       2 3
    # 2     999 2
    

提交回复
热议问题