r - 如何从多个列中找到最常出现的值

``````
S A B C D E

1 N N N N N

2 N Y Y N N

3 Y N Y N N

4 Y N Y Y Y

``````

``````
S A B C D E F

1 N N N N N N

2 N Y Y N N N

3 Y N Y N N N

4 Y N Y Y Y Y

``````

``````
df1\$F <- apply(df1[-1], 1, Mode)

df1

# S A B C D E F

#1 1 N N N N N N

#2 2 N Y Y N N N

#3 3 Y N Y N N N

#4 4 Y N Y Y Y Y

``````

``````
df1\$F <- c('N', 'Y')[max.col(table(c(row(df1[-1])), unlist(df1[-1])), 'first')]

``````

``````
Mode <- function(x) {

ux <- unique(x)

ux[which.max(tabulate(match(x, ux)))]

}

``````

``````
library(tidyverse)

df1 %>%

mutate(F = pmap_chr(.[-1], ~ Mode(c(...))))

``````

``````
gather(df1, key, F, - S) %>%

group_by(S, F) %>%

summarise(n = n()) %>%

slice(which.max(n)) %>%

ungroup %>%

dplyr::select(F) %>%

bind_cols(df1,. )

``````

``````
t(df1[-1]) %>%

as.data.frame %>%

summarise_all(Mode) %>%

unlist %>%

bind_cols(df1, F =. )

``````

``````
library(data.table)

setDT(df1)[, F := names(which.max(table(unlist(.SD)))), S][]

``````

``````
df1\$F <- c("Y","N")[(rowSums(df1[-1] =="N")> 2) + 1]

df1\$F

#[1]"N""N""N""Y"

``````

``````
c("Y","N")[(Reduce(`+`, lapply(df1[-1], `==`,"N"))> 2) + 1]

``````

``````
c("Y","N")[(str_count(do.call(paste0, df1[-1]),"N")> 2) + 1]

``````

数据

``````
df1 <- structure(list(S = 1:4, A = c("N","N","Y","Y"), B = c("N",

"Y","N","N"), C = c("N","Y","Y","Y"), D = c("N","N","N",

"Y"), E = c("N","N","N","Y")), class ="data.frame", row.names = c(NA,

-4L))

``````

``````
df %>%

mutate(F = ifelse(rowSums(.[2:length(.)] =="N")> 2,"N","Y"))

S A B C D E F

1 1 N N N N N N

2 2 N Y Y N N N

3 3 Y N Y N N N

4 4 Y N Y Y Y Y

``````

``````
df\$F <- ifelse(rowSums(df[2:length(df)] =="N")> 2,"N","Y")

``````

``````
df %>%

mutate(F = ifelse(rowMeans(.[2:length(.)] =="N")> 0.5,"N","Y"))

``````

``````
df\$F <- ifelse(rowMeans(df[2:length(df)] =="N")> 0.5,"N","Y")

``````

``````
x\$F <- unlist(do.call(Map, c(function(...) names(sort(-table(c(...)), partial=1)[1]), x[,-1])))

x

# S A B C D E F

# 1 1 N N N N N N

# 2 2 N Y Y N N N

# 3 3 Y N Y N N N

# 4 4 Y N Y Y Y Y

``````

`sort(..., partial=1)` 在第一次传递后停止排序。