Problem
We'd like to filter between two dates in R using the package dplyr.
Patch Date Prod_DL
1 BVG1 9/4/2015 3.43
2 BVG11 9/11/2015 3.49
3 BVG12 9/18/2015 3.45
4 BVG13 12/6/2015 3.57
5 BVG14 12/13/2015 3.43
6 BVG15 12/20/2015 3.47
- Data
df <- read.table(
text = "Patch,Date,Prod_DL
BVG1,9/4/2015,3.43
BVG11,9/11/2015,3.49
BVG12,9/18/2015,3.45
BVG13,12/6/2015,3.57
BVG14,12/13/2015,3.43
BVG15,12/20/2015,3.47",
sep = ",",
stringsAsFactors = FALSE,
header = TRUE,
row.names = NULL
)
Solution
We properly format the column containing the dates, originally a character column, and filter between the two dates.
library("dplyr")
df$Date <-as.Date(df$Date,"%m/%d/%Y")
df %>%
select(Patch, Date, Prod_DL) %>%
filter(Date > "2015-09-04" & Date < "2015-09-18")
Patch Date Prod_DL
1 BVG11 2015-09-11 3.49
We properly format the column containing the dates and use the function between: 'This is a shortcut for x >= left & x <= right, implemented efficiently in C++ for local values, and translated to the appropriate SQL for remote tables.' We need to change the days to account for the = sign on both sides, and to use as.Date, explanation here.
df$Date <- as.Date(df$Date, "%m/%d/%Y")
df %>%
select(Patch, Date, Prod_DL) %>%
filter(between(Date, as.Date("2015-09-05"), as.Date("2015-09-17")))
Patch Date Prod_DL
1 BVG11 2015-09-11 3.49
No hay comentarios:
Publicar un comentario