split or subset data into 30 minute intervals

2019-03-21 10:28发布

I have a data frame of the following form:

Temp    Depth      Light   x   time date                   time.at.depth
104     18.59      -2.7    27 21:38 2012-06-20             4
109     18.59      -2.7    27 22:02 2012-06-20             5
110     18.75      -4.0    27 22:07 2012-06-20             5
113     18.91      -2.7    27 22:21 2012-06-20             4
114     18.91      -4.0    27 22:26 2012-06-20             5
115     18.91      -2.7    27 22:31 2012-06-20             5
117     18.91      -2.7    27 22:40 2012-06-20             4
118     18.75      -4.0    27 22:45 2012-06-20             5
119     18.75      -2.7    27 22:50 2012-06-20             5
121     18.59      -4.0    27 22:59 2012-06-20             4
122     18.75      -2.7    27 23:04 2012-06-20             5
123     18.75      -4.0    27 23:09 2012-06-20             5
126     18.59      -2.7    27 23:23 2012-06-20             5
127     18.59      -2.7    27 23:28 2012-06-20             5
128     18.59      -4.0    27 23:33 2012-06-20             5
133     18.75      -4.0    27 23:57 2012-06-20             5
136     18.59      -4.0    27 00:11 2012-06-20             5
138     18.59      -2.7    27 00:21 2012-06-20             5
140     18.91      -2.7    27 00:30 2012-06-20             5

I would like to subset the data into 30 minute bins. Is there an easy way to do this? I looked at the split() function but it appears that things need to be in a numeric format for that to work, I have time in POSIXct format. Any ideas would be greatly appreciated.

1条回答
萌系小妹纸
2楼-- · 2019-03-21 10:57

Here's a one-liner for you (dat being your dataframe):

split(dat, cut(strptime(paste(dat$date, dat$time), format="%F %R"),"30 mins"))

Indeed cut.POSIXt accepts as break values

an interval specification, one of "sec", "min", "hour", "day", "DSTday", "week", "month", "quarter" or "year", optionally preceded by an integer and a space, or followed by "s".

Additionnaly, I used %F %R as a shortcut for %Y-%m-%d %H:%M: see ?strptime to see all possible formats.

查看更多
登录 后发表回答