R dplyr summarise multiple functions to selected variables

后端 未结 4 1746
死守一世寂寞
死守一世寂寞 2021-01-15 11:51

I have a dataset for which I want to summarise by mean, but also calculate the max to just 1 of the variables.

Let me start with an example of what I would like to a

4条回答
  •  失恋的感觉
    2021-01-15 12:27

    I was looking for something similar and tried the following. It works well and much easier to read than the suggested solutions.

    iris %>% 
    group_by(Species) %>%
    filter(Sepal.Length > 5) %>% 
    summarise(MeanSepalLength=mean(Sepal.Length), 
    MeanSepalWidth = mean(Sepal.Width),
    MeanPetalLength=mean(Petal.Length),
    MeanPetalWidth=mean(Petal.Width), 
    MaxPetalWidth=max(Petal.Width))
    
    # A tibble: 3 x 6
    Species    MeanSepalLength MeanSepalWidth MeanPetalLength MeanPetalWidth MaxPetalWidth
                                                            
    1 setosa                5.01           3.43            1.46          0.246           0.6
    2 versicolor            5.94           2.77            4.26          1.33            1.8
    3 virginica             6.59           2.97            5.55          2.03            2.5
    

    In summarise() part, define your column name and give your column to summarise inside your function of choice.

提交回复
热议问题