R - choose the number which appears most in a row -
i have df test
:
a b c 1 1 na 2 na na 1 2 2
i want create column, test$d
, number appears in row, excluding na. desired df is:
a b c d 1 1 na 1 2 na na 2 1 2 2 2
i have been looking similar function rowmeans
na.rm=t not find appropriate function situation. appreciate help
we can use apply
margin = 1
find frequency of numbers in each row , maximum frequency number using which.max
test$d <- apply(test, 1, fun = function(x) { x1 <- table(factor(x, levels = unique(x))) as.numeric(names(x1)[which.max(x1)])}) test$d #[1] 1 2 2
Comments
Post a Comment