In R data frame dt_df I want to retain all the rows with values in the following sequence as a new data frame. I can have dt_diff any numbers between -1 to 20. Now, I want to start by 1 (the previous day) and check if dt_diff has 1. If there is 1, filter all the rows with 1 in dt_diff retain this as a new data frame and stop processing, if there is not 1 check if there is 2, if there is 2 retain all rows with 2 as a new data frame and stop processing and so on until 20. If there are not any values between 1 to 20, then check if there is 0, if there is 0, retain rows with 0 as a new data frame, and stop processing. If there is no 0 or any values between 1 to 20 then check if there is -1 and retain all the rows with -1 as a new data frame. How can I achieve this? Here is sample data and unsuccessful for loop with if condition.
dt_df <- structure(list(date = structure(c(12241, 12241, 12257, 12257,
12257, 12257, 12257, 12257, 12257, 12257, 12259), class = "Date"),
ref_date = structure(c(12259, 12259, 12259, 12259, 12259,
12259, 12259, 12259, 12259, 12259, 12259), class = "Date")), row.names = c(NA,
-11L), class = c("tbl_df", "tbl", "data.frame"))
dt_df
dt_df$dt_diff <- as.numeric(dt_df$ref_date -dt_df$date)
pbl_dt_seq <- seq(-1, 20, 1)
pbl_dt_seq
for (i in 1:length(pbl_dt_seq)) {
i <- 2 # start with number 1
if(any(dt_df$dt_diff) == i ){
retain_dt <- dt_df %>%
filter(dt_diff == i)
retain_dt
break
}
if(any(dt_df$dt_diff) ==i+1 ){
retain_dt <-dt_df%>%
filter(dt_diff == i+1)
retain_dt
break
}
}
Aucun commentaire:
Enregistrer un commentaire