I have a df test
:
A B C
1 1 NA
2 NA NA
1 2 2
I want to create a another column, say test$D
, which is the number that appears most in that row, excluding NA. My desired df is:
A B C D
1 1 NA 1
2 NA NA 2
1 2 2 2
I have been looking for a similar function like rowMeans
with na.rm=T but could not find any appropriate function for this situation. Really appreciate any help
Another option using table
,
apply(test, 1, function(i) as.numeric(names(sort(-table(i)))[1]))
#[1] 1 2 2
We can use apply
with MARGIN = 1
to find the frequency of numbers in each row and get the 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.