Search code examples
rdataframestrptime

R strptime not piping into the data frame


library(dplyr)

names <- c('a','b','c')
dates1 <- c('2020-08-14','2020-08-15','2020-08-16')
dates2 <- c('2019-08-14','2019-08-15','2019-08-16')

df <- data.frame(names, dates1, dates2)
print(colnames(df))

timestamps <- df %>% select(dates1, dates2) %>%
  strptime('%Y-%m-%d')
print(timestamps)

Why is timestamps a pair of NAs? How do I get it to correctly apply strptime to these datetime strings?


Solution

  • You are applying sptrptime on dataframe instead you should apply it on columns

    library(dplyr)
    df %>% mutate(across(starts_with('date'), strptime, '%Y-%m-%d'))
    
    #  names     dates1     dates2
    #1     a 2020-08-14 2019-08-14
    #2     b 2020-08-15 2019-08-15
    #3     c 2020-08-16 2019-08-16
    

    Since you have only date information in the columns you can use as.Date :

    df %>% mutate(across(starts_with('date'), as.Date))