2020-12-27

Extracting Date and Time in R

Background: I'm currently learning R and I have a dataframe called data_2014 that looks like this

enter image description here

This was a result of reading csv files using read_csv from the package tidyverse

Question: I want to add separate columns for year, month, date, hour, minute, second by extracting the components from the date_time column. I have attempted to do the following:

library(tidyverse)
library(lubridate)

 data_2014 <- data_2014 %>%
  mutate(
    date_new = as.Date(date_time, tryformats = "%m/%d/%Y %H%M%S"),
    year = year(date_new),
    month = month(date_new),
    date = mday(date_new),
    hours = hour(date_new),
    minutes = minute(date_new),
    seconds = second(date_new)
  )

This gives me a lot of NA values and the year column does not appear properly. How should I fix this?



from Recent Questions - Stack Overflow https://ift.tt/3mRKTY3
https://ift.tt/eA8V8J

No comments:

Post a Comment