获取每一行在数据框中出现次数最多的值

Get the value with most occurrences in data frame for each row

假设我有一个简单的数据框

test_df <- data.frame(c(0,0,1,0,0,1,1,1,1,1),c(1,0,0,0,0,0,0,0,0,0))

我想获取每行的最大值(0 或 1)。 在我的示例中,第一个向量为 1(出现 6 次),第二个向量为 0(出现 9 次)。

我开始于:

> sapply(test_df,table)
  c.0..0..1..0..0..1..1..1..1..1. c.1..0..0..0..0..0..0..0..0..0.
0                               4                               9
1                               6                               1

到目前为止看起来不错。然后

> sapply((sapply(test_df,table)),max)
[1] 4 6 9 1

我迷路了,我是不是失去了联想? 1 -> 6 , 0 -> 9 我想要的是返回一个向量 "winner": 1,0,...

1 for the first vector (6 occurrences)
0 for the second vector (9 occurrences)
...

我们可以使用 applyMARGIN=1sapply 输出的每一行中提取 max 值。

frqCol <- sapply(test_df, table)
apply(frqCol, 1, max)
# 0 1 
# 9 6 

或使用 matrixStats

中的 rowMaxs
library(matrixStats)
rowMaxs(frqCol)
#[1] 9 6

如果我们需要每列 'max' 值

apply(frqCol, 2, max)

colMaxs(frqCol)

以新为例

test_df <- data.frame(v1= c(0,0,1,0,0,1,1,1,1,1),
                  v2= c(1,0,0,0,0,0,0,0,0,0),
                  v3= c(1,0,0,0,0,0,0,0,0,1)) 
frqCol <- sapply(test_df, table)
apply(frqCol, 2, max)
#v1 v2 v3 
#6  9  8 
colMaxs(frqCol)
#[1] 6 9 8

这可以在一个 apply 语句中完成。虽然,不清楚你是否想要每一行或每一列的最大出现次数,所以这里有两个(使用@akrun 的更干净的数据集),返回一个向量显示每个 'winner'(1 或 0) 15=].

## Data
test_df <- data.frame(v1= c(0,0,1,0,0,1,1,1,1,1),
                      v2= c(1,0,0,0,0,0,0,0,0,0),
                      v3= c(1,0,0,0,0,0,0,0,0,1)) 
#    v1 v2 v3
# 1   0  1  1
# 2   0  0  0
# 3   1  0  0
# 4   0  0  0
# 5   0  0  0
# 6   1  0  0
# 7   1  0  0
# 8   1  0  0
# 9   1  0  0
# 10  1  0  1

## Solution - For each row
apply(test_df, 1, function(x) { sum(sum(x == 1) > sum(x == 0)) })

## Result
# [1] 1 0 0 0 0 0 0 0 0 1

## Solution - For each column
apply(test_df, 2, function(x) { sum(sum(x == 1) > sum(x == 0)) })

## Result 
# v1 v2 v3 
# 1  0  0