0
votes

I am trying to select a range of rows corresponding to a range of dates (in this example 21/9/2007 to 19/3/2008) and then work with the dates within those ranges. However, I can't seem to get a clean set of data. Any suggestions?

edata

AvgWinterVolt <- edata %>% filter(between(Date, as.Date("21/9/2007"), as.Date("19/3/2008")))

1
What do you mean by "clean set of data"? Try showing what you expect and what your current approach gives. It will be easier to help you answer your question if you try to make your example code reproducible and self contained. See the answers to this question for guidance.sboysel

1 Answers

0
votes

The key is to explicitly specify the date format (format = "%d/%m/%Y") since its not recognized.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

# Create sample dataframe with one Date column
edata <- tibble(Date = as.Date(c("21/10/2006", "21/10/2007", "19/2/2008", "21/9/2009", "21/9/2010"),
  format = "%d/%m/%Y"
))

# Did it detect as date correctly?
glimpse(edata)
#> Observations: 5
#> Variables: 1
#> $ Date <date> 2006-10-21, 2007-10-21, 2008-02-19, 2009-09-21, 2010-09-21

( #this extra set of brackets is shorthand for printing the below variable
AvgWinterVolt <- edata %>% 
  filter(between(Date, as.Date("21/9/2007", format = "%d/%m/%Y"), 
                 as.Date("19/3/2008", format = "%d/%m/%Y")))
) #closing top bracket mentioned
#> # A tibble: 2 x 1
#>   Date      
#>   <date>    
#> 1 2007-10-21
#> 2 2008-02-19

Created on 2019-10-13 by the reprex package (v0.3.0)