[英]Grouping months data into year
My data frame looks somewhat like this我的数据框看起来有点像这样
1976 January 250
1976 February 350
1976 March 230
1976 April 255
This goes up to 2007这一直持续到 2007 年
I want to aggregate and find the mean of the data per year.我想汇总并找出每年数据的平均值。 I want to create a variable that would contain a table of data mean by each year.我想创建一个变量,其中包含每年的数据表。 So that it looks like这样看起来像
1976 mean of all 1976 months
1977 mean of all 1976 months
1978 mean of all 1976 months
1979 mean of all 1976 months
and so on等等
How can I do it?我该怎么做?
The data frame is "data" and the first column is "year"数据框是“data”,第一列是“year”
variable_name <- aggregate(x=data$secondcolumn_name, by=list(data$Year), FUN="mean")
But it is not getting aggregated.但它没有得到聚合。 I think since the column "year" has characters is the problem.我认为因为“年”列有字符是问题所在。
If the Year
column has always the same form that in the image and its class is character
, the dataframe is called data
and the name of the second column is second_column_name
(to abbreviate the name in the image), then you can do:如果Year
列始终具有与图像中相同的形式,并且其 class 为character
,则 dataframe 称为data
并且第二列的名称为second_column_name
(图像中名称的缩写),那么您可以执行以下操作:
library(dplyr)
data %>%
group_by(substr(Year,1,4)) %>%
summarise(avg = mean(second_column_name))
Or using mutate
instead of summarise
if you want to preserve the monthly data.或者,如果您想保留每月数据,请使用mutate
而不是summarise
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.