user14845
user14845

Reputation: 105

Aggregate date and time in R

My data has a start and end time stamp such as this:

200401010000 200401010030
200401010030 200401010100
200401010100 200401010130 and so on...

I'm trying to convert these fields into %YYYY%MM%DD%HH%MM format using lubridate and as.POSIXct but it I get only NAs. Any help will be appreciated. My goal is to aggregate the data for each month. The code I've used so far is as follows:

start_time = as.POSIXct(dat$TIMESTAMP_START, format = "%YYYY%MM%DD %HH%MM",origin = "2004-01-01 00:00", tz="EDT")
stop_time = as.POSIXct(dat$TIMESTAMP_END, format = "%YYYY%MM%DD%HH%MM",origin = "2004-01-01 00:30", tz="EDT")
dat$interval <- interval(start_time, stop_time)

Upvotes: 0

Views: 116

Answers (1)

Renata Gerecke
Renata Gerecke

Reputation: 58

Two problems I can see:

  1. If you're using lubridate already, you should probably use the function ymd_hm(), which is just cleaner IMO.

  2. You can't apply that function to a vector (which I presume dat$TIMESTAMP_START and dat$TIMESTAMP_END are); to do this, you can use:

    start_time <- sapply(dat$TIMESTAMP_START, ymd_hm())
    end_time <- sapply(dat$TIMESTAMP_END, ymd_hm()) 
    

    That will apply the function to each item in your vector.

Upvotes: 1

Related Questions