Home > Mobile >  Converting a dataframe column into datetime format in R
Converting a dataframe column into datetime format in R

Time:12-21

So I am new to R, working on this practice case study, and I am stuck! I have 3 dataframes, and I need to bind them, but before I do, I'm renaming columns and converting the data types into the same type.

Firstly, I've renamed the columns, but I have questions about that:

str(df)

returns:

$ old_column_name : Date[1:704054], format: NA NA NA ...

- attr(*, "spec")=
.. cols(
       new_column_name = col_character()
..)

And when I run colnames(df), the new column names do show up, but when I try to convert using the new names, it throws an error saying "unknown or uninitialised column"

I'm trying to convert the character column into datetime format to match the other two df's that I need to bind to. This is the code I've been using, with libraries tidyverse and lubridate installed:

df <- mutate(df, new_column_name = as.Date.POSIXct(df$new_column_name,
 format = "%Y-%m-%dT%H:%M"))

again, this is throwing the error "unknown or uninitialised column", but when i "colnames(df)", the new name is there! I need help. Please and thank you.

CodePudding user response:

I am not too sure on the format you want your date in but try this:

library(dplyr)
new_df <- df %>%
  rename(new_column_name = old_column_name) %>%
  mutate(new_column_name = as.POSIXct(new_column_name, format = "%Y-%m-%dT%H:%M"))
  • Related