Aggregate by NA in R

后端 未结 5 1976
闹比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

    Using sqldf:

    a <- as.data.frame(a)
    sqldf("SELECT V2 [Group], SUM(V1) x 
          FROM a 
          GROUP BY V2")
    

    Output:

      Group x
    1    NA 2
    2     2 3
    

    stats package

    A variation of AdamO's proposal:

    data.frame(xtabs( V1 ~ V2 , data = a,na.action = na.pass, exclude = NULL))
    

    Output:

        V2 Freq
    1    2    3
    2     2
    

提交回复
热议问题