-1

I have a list of years, that it loops through and iterate & generate answers for new column in the data frame. But the final results only show the last iteration.

How can I generate/save all the columns and rows in a data frame?

# list of years 
years = as.list(unique(as.character(temp_reshape$Year)))

for (i in seq_along(years)) {
  
  # iterate by year 
  year_index <- years[[i]]
  
  tt <- temp_reshape %>% 
    filter(as.character(Year) == year_index) %>% 
    arrange(Date_Value) %>% 
    mutate(Xt_mu = Value - summer_means,
           Xt_u_C = Xt_mu - 0, 
           St = cumsum(ifelse(Xt_u_C < 0, 0, Xt_u_C))) 
}
James
  • 3
  • 3
  • Where exactly do you want to save them? Here you just keep overwriting the `tt` variable. `for` loops in R don't return anything. It often makes more sense to use something like `lapply()`. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Feb 09 '21 at 05:02
  • I want to save the results for St (new column) for each year (1996-2015). Each st rows (cumulative) will only calculated based on the particular year. I am able to get the results I need from the code above. It just that it won't save all the results for all the years, just the final year (2015). – James Feb 09 '21 at 05:21
  • thanks for the pointer about for loop – James Feb 09 '21 at 05:38

1 Answers1

1

A reproducible example would have been helpful but I think you don't need to split the data. You can use group_by to perform the calculation for every Year separately.

library(dplyr)

temp_reshape %>%
  arrange(Year, Date_Value) %>% 
  group_by(Year) %>%
  mutate(Xt_mu = Value - summer_means,
         Xt_u_C = Xt_mu - 0, 
         St = cumsum(ifelse(Xt_u_C < 0, 0, Xt_u_C))) -> tt

tt
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • I tried this again and it works after restarting R. I think cumsum is the main culprit for the incorrect results previously. Thanks for your help! – James Feb 09 '21 at 05:37