【问题标题】:I want summarise a data frame [duplicate]我想总结一个数据框[重复]
【发布时间】:2022-01-15 13:19:22
【问题描述】:

我想将以下数据框汇总到汇总表中。

plot <- c(rep(1,2), rep(2,4), rep(3,3))
bird <- c('a','b', 'a','b', 'c', 'd', 'a', 'b', 'c')
area <- c(rep(10,2), rep(5,4), rep(15,3))
birdlist <- data.frame(plot,bird,area)
birdlist
  plot bird area
1    1    a   10
2    1    b   10
3    2    a    5
4    2    b    5
5    2    c    5
6    2    d    5
7    3    a   15
8    3    b   15
9    3    c   15

我尝试了以下

birdlist %>% 
  group_by(plot, area) %>% 
  mutate(count(bird))

我正在尝试获取如下所示的数据框

plot bird area
   1    2   10
   2    4   5
   3    3   15

请参考plotareaplot 对如何计算bird 提供帮助/建议。谢谢。

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    我们可以使用unique() group_by plotsummarise

    birdlist %>% 
      group_by(plot) %>% 
      summarise(bird = n(), area = unique(area))
    
         plot  bird  area
      <dbl> <int> <dbl>
    1     1     2    10
    2     2     4     5
    3     3     3    15
    

    【讨论】:

      【解决方案2】:

      您非常接近,但您想要summarize 而不是mutate,您可以使用n() 来计算您指定的组中的行数。

      library(tidyverse)
      birdlist %>%
        group_by(plot, area) %>%
        summarize(bird = n(),
                  .groups = "drop")
      #> # A tibble: 3 x 3
      #>    plot  area  bird
      #>   <dbl> <dbl> <int>
      #> 1     1    10     2
      #> 2     2     5     4
      #> 3     3    15     3
      

      如果您设置为count,则可以不使用group_by

      birdlist %>%
        count(plot, area, name = "bird")
      

      【讨论】:

      • 谢谢,我试过了,但出现错误。 birdlist %&gt;% + group_by(plot, area) %&gt;% + summarize(bird = n(), + .groups = "drop") Error: `n()` must only be used inside dplyr verbs. Run `rlang::last_error()` to see where the error occurred.
      • 啊,你可能有冲突的包。作为 dplyr::summarize 运行它
      • 我还是有这个问题。
      • 完成!!!非常感谢。
      • 没问题。当您加载包时,您会收到警告,哪些函数名称有冲突,因此请务必查看。对于summarize 函数,我经常使用dplyrrms 得到这个。发生这种情况时,您必须专门引用要从中调用函数的包(即 dplyr::summarize),否则 R 将使用最新加载的包。
      猜你喜欢
      • 2019-02-19
      • 2020-04-26
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 2022-07-11
      • 2021-04-22
      • 2014-11-15
      相关资源
      最近更新 更多