Help Looping Based on Date Range

Hi All,
I am trying to create a data frame which is made up of the resulting value of a changing portion of my code. I want a data frame which shows the Daily_Indice_Value based on a changing daily value of the date in the
`

"filter(Date <= as.Date("What I want to Change")
`
section of my code.

library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date
library(reprex)


#testing 
test_blue_chips <- data.frame(Graded_Title = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'), 
                              Date = seq(from = as.Date("2004-11-17"), to = as.Date("2004-11-24"), by = 'day'),
                              Price = c(1,2,3,4,5,6,7,8))

blue_chips_any_mv <- test_blue_chips %>%
  group_by(Graded_Title) %>%
  filter(Date <= as.Date("2004-11-24")) %>%
  slice(1:3) %>%
  summarise(Market_Value2 = mean(Price)) %>%
  ungroup() %>%
  summarise(Daily_Indice_Value = sum(Market_Value2))
blue_chips_any_mv
#> # A tibble: 1 x 1
#>   Daily_Indice_Value
#>                <dbl>
#> 1                  8

map_df is like a for loop but helps you automatically get a dataframe in return




dates <- 
  seq(from = as.Date("2004-11-17"), to = as.Date("2004-11-24"), by = 'day')

map_df(dates, function(date){
  test_blue_chips %>%
    group_by(Graded_Title) %>%
    filter(Date <= date) %>% # plugging in value date from dates 
    slice(1:3) %>%
    summarise(Market_Value2 = mean(Price)) %>%
    ungroup() %>%
    summarise(Daily_Indice_Value = sum(Market_Value2)) %>% 
    mutate(Date=date) # which item in for loop created this
  
})

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.