【问题标题】:How to take the average mean of each year?如何取每年的平均数?
【发布时间】:2019-10-23 05:53:52
【问题描述】:

我有一个数据,其中包含不同年份的碳和氮浓度测量值。它每年都有许多不同的措施。我想获得每年 C 和 N 的平均平均值,以便绘制这些年的变化。

我尝试了推荐的不同功能,但我的代码始终无法正常工作..

enter image description here

【问题讨论】:

  • 请提供可重现的示例。

标签: r dplyr group-by tidyverse mean


【解决方案1】:

您可以使用dplyrsummarise_all 函数来执行此操作。你可以试试这样的:

ad <- data.frame(year = rep(2009:2012, 15), C = sample(-100:100, 60), N = sample(-100:100, 60))

> head(ad)
  year   C   N
1 2009   0  49
2 2010  44  94
3 2011 -81 -84
4 2012 -43  55
5 2009 -64  14
6 2010 -62  31


library(tidyverse)
ad%>%group_by(year)%>%
  summarise_all(funs(mean))

# A tibble: 4 x 3
   year      C      N
  <int>  <dbl>  <dbl>
1  2009  -1.2  10.9  
2  2010   1     3.27 
3  2011  -1.87  0.667
4  2012 -11.1  -9.73 

【讨论】:

    【解决方案2】:

    如果你习惯了sql,那么sqldf 也可以。

    sqldf("Select Year, AVG(C), AVG(N) FROM ad GROUP BY Year")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-03
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      相关资源
      最近更新 更多