I am trying to extract the month from a date formatted as a character. I first convert the strings in column 1 to a date format (class character). However, I am unable to extract the month.
df <- data.frame(col1=c(44008, 44001, NA, 77), col2=c(43476, 43479, 77, NA))
df
col1 col2
1 44008 43476
2 44001 43479
3 NA 77
4 77 NA
My attempt
df %>%
# convert to date
mutate_at(vars(col1), funs(case_when((nchar(col1)>4)~(as.character(as.Date(as.numeric(col1), origin="1899-12-30"))), TRUE~as.character(col1))) ) %>%
mutate(
# extract month
col1_month = case_when(nchar(col1)==10~lubridate::month(col1), TRUE~as.character(col1)))
I've tried various tricks but can't seem to get this to work.
Desired output:
col1 col2 col1_month
1 2020-06-26 43476 6
2 2020-06-19 43479 6
3 <NA> 77 NA
4 77 NA 77
col1_month
to equalcol1
for values with 4 or less digits? I would think NA is a better choice. – neilfws