How to sum a column based on specific year?

后端 未结 1 1855
野趣味
野趣味 2021-01-23 15:28

Suppose I have following time-series data frame in R.

Date           Var1
1/1/2010        7
1/2/2010        154
1/3/2010        125
1/4/2010        87
1/5/2010           


        
相关标签:
1条回答
  • 2021-01-23 16:08

    We can use substr to get the 'year' part from 'Date' column, use that in subset to extract the rows that have '2010' as year, select the 'Var1' column, and get the sum

     sum(subset(df1, substr(Date,5,8)==2010, select=Var1))
    

    Or a dplyr/lubridate option would be using filter and summarise to get similar result.

     library(lubridate)
     library(dplyr)
     df1 %>% 
         filter(Date=year(mdy(Date))==2010) %>%
         summarise(Var1= sum(Var1))
    
    0 讨论(0)
提交回复
热议问题