I am trying to filter last 3 months data in R w.r.t maximum date present in my date column.
I initially added a column to my existing data frame and used the below expression for filtering the data. I want to eliminate this extra step and do the filtering directly.
last_three_month <- df_1[date_format > max(as.Date(date_format)) %m-% months(4) &
date_format <= max(date_format) , ]
When I use df_1[MonthYear]
and filter the data I see an error like
"Error: ‘max’ not meaningful for factors"
Data
MonthYear Number Risk
1/18/2019 101 High AESI
1/18/2019 905
1/18/2019 909
1/18/2019 904
2/18/2019 101 High AESI
2/18/2019 905
2/18/2019 904
2/18/2019 909
2/18/2019 907
2/18/2019 541 High AESI
2/18/2019 908 High AESI
2/18/2019 906 High AESI
2/18/2019 046
2/18/2019 018 High AESI
2/18/2019 019
2/18/2019 002 High AESI
3/18/2019 904
3/18/2019 907
3/18/2019 905
Code
library(dplyr)
library(tibble)
library(reshape)
Input <- read.csv("C:/Users/Documents/Exports/HR.csv")
Output <- Input #%>% filter(Year == 2019)
df_output <- as.data.frame(Output)
date_format <- as.Date(paste("01-", df_output$Month.Year, sep = ""),
format = "%d-%b-%y")
df_1 <- cbind(df_output, date_format)
last_three_month <- df_1[date_format > max(as.Date(date_format)) %m-% months(4) &
date_format <= max(date_format) , ]
I am actually trying to filter data directly in the data frame rather than adding one more column and achieving it. Can you please advise - Thanks