I am very new to R but trying my best to learn! Need help adding a column for just the date, parsed from datetime data.
My data looks like this:
city | state | datetime
Sand | CA. | 2017-12-22 14:07:00
I would like to add a fourth column with just the date. I thought I could use Lubridate but the function ymd_hms("datetime")
will not parse the data.
Thank you for your help
CodePudding user response:
You can just use as.Date
to pull out the date from the date and time.
library(dplyr)
df %>%
mutate(date = as.Date(datetime))
Or if your date time column is just a character, then you need to convert to POSIXct first.
df %>%
mutate(date = as.Date(as.POSIXct(datetime)))
Output
city state datetime date
1 Sand CA. 2017-12-22 14:07:00 2017-12-22
Data
df <- structure(list(city = "Sand", state = "CA.", datetime = structure(1513980420, class = c("POSIXct",
"POSIXt"), tzone = "")), class = "data.frame", row.names = c(NA,
-1L))
CodePudding user response:
if you have store the data in dataframe named data then below is code to add a new colum of date in your dataframe
data$date=as.Date(data$datetime)