x1<- split(df, cumsum(df$Date < 1900-01-01))
x2<- split(df, cumsum(df$Date >= 1945-01-01 & df$Date <= 1955-01-01))
x3<- split(df, cumsum(df$Date > 2000-01-01))
I am trying to split the data frame based on the above mentioned conditions. However, the functions only work for the first one, not on the other two.
Let's take this sample:
df <- data.frame(V1 = c("1800-01-01","1950-01-01","2005-01-01"))
df <- df %>%
mutate(V1 = as.Date(V1))
V1
1 1800-01-01
2 1950-01-01
3 2005-01-01
Code:
library(tidyverse)
df <- df %>%
mutate(indic = case_when(
V1 < "1900-01-01" ~ 1,
V1 >= "1945-01-01" & V1 <= "1955-01-01" ~ 2,
V1 > "2000-01-01" ~ 3,
TRUE ~ 4
))
list_of_df <- split(df, df$indic)
i = 1
MyF <- function(input){
out <- as.data.frame(input)
out <- out %>% select(-indic)
nom <- paste0("dfE",i)
assign(nom, out, envir = .GlobalEnv)
i <<- i + 1
}
lapply(list_of_df, MyF)
This will create in your environment the dataframes dfE1
, dfE2
and dfE3
based on the conditions you used first (about the dates).
> dfE1
V1
1 1800-01-01
> dfE2
V1
2 1950-01-01
> dfE3
V1
3 2005-01-01
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.