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

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -