Handling NA values in apply and unique

前端 未结 2 1943
小蘑菇
小蘑菇 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" 
    

提交回复
热议问题