Split date in wide format with R
do you have a solution for splitting dates from one column to two columns in R when the original variable contains "after" and "before" like in the example below?
library(data.table)
library(splitstackshape)
date <- c("2012-2015","2016","after 2006", "before 1930")
df <- data.table(date)
df_l <- splitstackshape::cSplit(df, "date", sep = "-", direction = "wide")
df_l
# how can I achieve this
df_l$date_1 <- c( "2012", "2016", "2006", "1900")
df_l$date_2 <- c( "2015", "NA", "2022", "1930")
df_l
library(tidyverse)
data.frame(date) %>%
mutate(date1 = str_replace_all(date,
c('after (.*)' = '\\1-2022', before = '1900'))) %>%
separate(date1, c('date_1', 'date_2'), convert = TRUE, fill = 'right')
date date_1 date_2
1 2012-2015 2012 2015
2 2016 2016 NA
3 after 2006 2006 2022
4 before 1930 1900 1930