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

'hasOwnProperty' in javascript -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -

How to understand 2 main() functions after using uftrace to profile the C++ program? -