Handling NA values in apply and unique

前端 未结 2 1928
小蘑菇
小蘑菇 2021-01-04 06:20

I have a 114 row by 16 column data frame where the rows are individuals, and the columns are either their names or NA. For example, the first 3 rows looks like this:

相关标签:
2条回答
  • 2021-01-04 07:10

    You were very, very close in your initial solution. But as Aniko remarked, you have to remove NA values before you can use unique.

    An example where we first create a similar data.frame and then use apply() as you did -- but with an additional anonymous function that is used to combine na.omit() and unique():

    R> DF <- t(data.frame(foo=sample(c(NA, "Foo"), 5, TRUE), 
                          bar=sample(c(NA, "Bar"), 5, TRUE)))
    R> DF
        [,1]  [,2] [,3]  [,4]  [,5] 
    foo "Foo" NA   "Foo" "Foo" "Foo"
    bar NA    NA   NA    "Bar" "Bar"
    R> apply(DF, 1, function(x) unique(na.omit(x)))
      foo   bar 
    "Foo" "Bar" 
    
    0 讨论(0)
  • 2021-01-04 07:15

    unique does not appear to have an na.rm argument, but you can remove the missing values yourself before calling it:

    A <- matrix(c(NA,"A","A",
                 "B", NA, NA,
                  NA, NA, "C"), nr=3, byrow=TRUE)
    apply(A, 1, function(x)unique(x[!is.na(x)]))
    

    gives

    [1] "A" "B" "C"
    
    0 讨论(0)
提交回复
热议问题