简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM