0

I wanted to create a new data frame that displays the total sum for each specific year from 2015-2022. Is there a way for me to do this without having to create a SumValue for each year and creating a vector from these object?

This is how I coded it:


Sum15 = mydata %>%
filter(Date==2015) %>%
summarise(Value = sum(Value))

Sum16 = mydata %>%
filter(Date==2016) %>%
summarise(Value = sum(Value))

Sum17 = mydata %>%
filter(Date==2017) %>%
summarise(Value = sum(Value))

etc....

Year = c("2015","2016","2017","2018","2019","2020","2021","2022")

Value = c(Sum15$Value, Sum16$Value, Sum17$Value, Sum18$Value, Sum19$Value,
          Sum20$Value, Sum21$Value, Sum22$Value)

YearSum = data.frame(Year,Value)
  • 2
    Try `mydata %>% group_by(Date) %>% summarise(Value = sum(Value))`. – stefan Jul 31 '23 at 15:47
  • 2
    This is a frequent question, with several good answers with many options: https://stackoverflow.com/q/11562656/3358272, https://stackoverflow.com/q/1660124/3358272, https://stackoverflow.com/q/12064202/3358272 (multiple functions). If those answers and stefan's comment don't resolve this for you, please [edit] your question to include what you tried from that list of suggestions, then @-ping me (and/or stefan) and we can help sort out the issues, reopening if needed. Hope this helps! – r2evans Jul 31 '23 at 15:51

0 Answers0