Handling NA values in apply and unique

随声附和 提交于 2019-12-01 03:23:14

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"
Dirk Eddelbuettel

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" 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!