【问题标题】:Is there a way to count values by presence per rows in R?有没有办法通过 R 中每行的存在来计算值?
【发布时间】:2023-03-21 05:48:01
【问题描述】:

我想要一种方法来根据数据帧的存在来计算数据帧上的值

a = data.frame(c('a','b','c','d','f'), 
               c('a','b','a','b','d'))
colnames(a) = c('let', 'let2')

在这个可重现的示例中,字母“a”出现在第一行和第三行,总共出现了两次。我已经制作了这段代码来计算存在是否为 TRUE 的值,但我希望它自动将其归因于数据框中存在的所有变量:

#for counting the variable a and atribunting the count to the b dataframe

b = data.frame(unique(unique(unlist(a))))
b$count = 0

for(i in 1:nrow(a)){
  if(TRUE %in% apply(a[i,], 2, function(x) x %in% 'a') == TRUE){
    b$count[1] = b$count[1] + 1
  }  
}

b$count[1]
[1] 2

问题是我必须为所有变量手动制作,我想要一种自动制作的方法。有办法吗?预期的输出是:

1                         a     2
2                         b     2
3                         c     1
4                         d     2
5                         f     1

【问题讨论】:

    标签: r dataframe apply counting


    【解决方案1】:

    这可以在base R 中完成,方法是将unique 值与列分开,unlistvector,并使用table 获得频率计数。如果需要,将table 对象转换为带有stack 的两列data.frame

    stack(table(unlist(lapply(a, unique))))[2:1]
    

    -输出

    #  ind values
    #1   a      2
    #2   b      2
    #3   c      1
    #4   d      2
    #5   f      1
    

    如果是基于行的,使用applyMARGIN = 1

    table(unlist(apply(a, 1, unique)))
    

    或按行分组以获取unique 并以table 计数

    table(unlist(tapply(unlist(a), list(row(a)), unique)))
    

    或者使用dapply 来自collapse 的更快方法

    library(collapse)
    table(unlist(dapply(a, funique, MARGIN = 1)))
    

    【讨论】:

    • 非常感谢,但该解决方案使每列的值唯一,而不是每行。是否有可能根据行计算值?
    • @sciencenmagic 更新了帖子。抱歉,我正在检查预期的结果,它们都给出了相同的输出
    【解决方案2】:

    这行得通吗:

    library(dplyr)
    library(tidyr)
    a %>% pivot_longer(cols = everything()) %>% distinct() %>% count(value)
    # A tibble: 5 x 2
      value     n
      <chr> <int>
    1 a         2
    2 b         2
    3 c         1
    4 d         2
    5 f         1
    

    使用的数据:

    a
      let let2
    1   a    a
    2   b    b
    3   c    a
    4   d    b
    5   f    d
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-30
      • 1970-01-01
      • 2019-11-04
      • 2018-05-08
      • 2020-08-03
      相关资源
      最近更新 更多