2

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

AndrewGB
  • 16,126
  • 5
  • 18
  • 49
cc77
  • 21
  • 1

2 Answers2

2

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)))

Or in base R:

df$date <- as.Date(as.POSIXct(df$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))
AndrewGB
  • 16,126
  • 5
  • 18
  • 49
0

if you have store the data in dataframe named data then below is code to add a new column of date in your dataframe.

data$date = as.Date(data$datetime)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Veena Kumari
  • 21
  • 1
  • 4