【问题标题】:R - Group by on continuous variable headers with categorical variable factors as rows and aggregated as min, max, meanR - 对连续变量标题进行分组,将分类变量因子作为行并聚合为最小值、最大值、平均值
【发布时间】:2021-12-31 21:37:57
【问题描述】:

我想通过将连续列保持为行并将分类因子作为列标题进行分组,聚合记录为平均值、最小值或最大值。这是一个基本问题,我无法弄清楚答案。以虹膜数据为例。我想获得每个物种类别的 sepal.width 和 sepal.length 的平均值。

library(dplyr)

mydata2 <-iris 

# Groupby function for dataframe in R

summarise_at(group_by(mydata2,Species),vars(Sepal.Length),funs(mean(.,na.rm=TRUE)))

OUTPUT 

Species    Sepal.Length
  <fct>             <dbl>
1 setosa             5.01
2 versicolor         5.94
3 virginica          6.59

我想用 Sepal.Length 作为我的行而不是 Species 和 Species 的各种因素作为我的列获得相同的输出。我也想要 Sepal.Width、Petal.Length、Petal.Width 该怎么做?

这就是我要找的 -

Species            setosa     versicolor  virginica
  
1 Sepal.Length       5.01      5.94       6.59

下面应该有 Sepal.Width 和其他连续的列。 我尝试过转置,但这会将所有内容都更改为字符数据类型。

【问题讨论】:

    标签: r group-by


    【解决方案1】:

    实现您想要的结果的一个选择是在summarise 之后通过例如重塑您的数据。 pivot_longerpivot_wider。如果您经常这样做,您可以将代码放入一个方便的函数中,以便一步完成:

    注意:我还放弃了summarise_at,并使用acrosswhere 切换到新的API。

    library(dplyr)
    library(tidyr)
    
    summarise(group_by(iris, Species), across(where(is.numeric), mean, na.rm=TRUE)) %>% 
      pivot_longer(-Species, names_to = "var") %>% 
      pivot_wider(names_from = Species, values_from = value)
    #> # A tibble: 4 × 4
    #>   var          setosa versicolor virginica
    #>   <chr>         <dbl>      <dbl>     <dbl>
    #> 1 Sepal.Length  5.01        5.94      6.59
    #> 2 Sepal.Width   3.43        2.77      2.97
    #> 3 Petal.Length  1.46        4.26      5.55
    #> 4 Petal.Width   0.246       1.33      2.03
    

    【讨论】:

      【解决方案2】:

      你可以使用tapplyinsinde lapply:

      do.call(rbind, lapply(iris[sapply(iris, is.numeric)],
                            function(x) tapply(x, iris$Species, mean)))
      #             setosa versicolor virginica
      #Sepal.Length  5.006      5.936     6.588
      #Sepal.Width   3.428      2.770     2.974
      #Petal.Length  1.462      4.260     5.552
      #Petal.Width   0.246      1.326     2.026
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-15
        • 2023-04-03
        • 2021-06-15
        • 1970-01-01
        • 2015-04-12
        • 2018-10-22
        • 2022-11-21
        相关资源
        最近更新 更多