Handling NA values in apply and unique
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"
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"