【问题标题】:Get the value with most occurrences in data frame for each row获取每行数据框中出现次数最多的值
【发布时间】:2016-04-02 05:29:19
【问题描述】:

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

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 我想要的是返回一个带有“赢家”的向量:1,0,...

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

【问题讨论】:

  • 当您创建一个没有任何列名的data.frame 时,您将获得c.0..0..1..0..0..1..1..1..1..1 作为列名。请检查您创建的“test_df”的输出。

标签: r dataframe sapply


【解决方案1】:

这可以在一个apply 语句中完成。虽然,不清楚您是否想要每行或每列的最大出现次数,所以这里都是(使用 @akrun 的更清洁的数据集),返回一个向量,显示每行/列的“获胜者”(1 或 0)。

## 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 

【讨论】:

    【解决方案2】:

    我们可以使用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
    

    如果我们需要每列的“最大值”

    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
    

    【讨论】:

    • sapply + apply 看起来非常接近,但是如果我向数据框添加另一个向量,如何使用 apply 呢? test_df &lt;- data.frame(c(0,0,1,0,0,1,1,1,1,1),c(1,0,0,0,0,0,0,0,0,0),c(1,0,0,0,0,0,0,0,0,1))
    • @user869097 您能否在您的帖子中更新此内容。从 cmets 复制/粘贴非常困难。另外请更新预期输出
    • @user869097 更新了帖子
    • 效率低下怎么样:do.call(pmax, data.frame(t(frqCol))) ;)
    • @G.Cocca 是的,可以使用,但是我们需要转换成data.frame。
    猜你喜欢
    • 1970-01-01
    • 2022-11-28
    • 2021-02-05
    • 2012-06-23
    • 2011-04-16
    • 2021-08-30
    • 1970-01-01
    相关资源
    最近更新 更多