R 如何根据具体年份对列求和?
假设在R中有以下时间序列数据帧R 如何根据具体年份对列求和?,r,R,假设在R中有以下时间序列数据帧 Date Var1 1/1/2010 7 1/2/2010 154 1/3/2010 125 1/4/2010 87 1/5/2010 57 1/6/2010 12 .... .... 7/24/2015 5 如果我只想在2010年求和(Var1),如何在R中求和?我们可以使用substr从'Date'列中获取'year'部分,在subset中使用
Date Var1
1/1/2010 7
1/2/2010 154
1/3/2010 125
1/4/2010 87
1/5/2010 57
1/6/2010 12
....
....
7/24/2015 5
如果我只想在2010年求和(Var1),如何在R中求和?我们可以使用
substr
从'Date'列中获取'year'部分,在subset
中使用它来提取将'2010'作为年份的行,选择'Var1'列,然后获取Sum
sum(subset(df1, substr(Date,5,8)==2010, select=Var1))
或者,dplyr/lubridate
选项将使用filter
和summary
获得类似的结果
library(lubridate)
library(dplyr)
df1 %>%
filter(Date=year(mdy(Date))==2010) %>%
summarise(Var1= sum(Var1))
感谢您的快速响应,我尝试了两种方法,都有效~