Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

r - How do I quickly group the time column in a dataframe into intervals?

Assuming in R, I have a data.frame with the first column representing the time (as POSIXct). The rest of the columns (e.g., columns 2) are numeric data.

I would like to group time into 3-minute intervals. Each interval will the the average of values that falls into that particular interval.

Right now, I have a for-loop that iterates through the time column and generate the interval on the fly. I am wondering if there's a more elegant way to accomplish the same thing?

Thanks in advance.

Derek

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think that a command like the following, would return a list of the values that fall into 3 minute intervals. (v is the name of the dataframe and datecol is the name of the date column)

library(plyr)

v<-data.frame(datecol=as.POSIXct(c(
  "2010-01-13 03:02:38 UTC",
  "2010-01-13 03:03:14 UTC",
  "2010-01-13 03:05:52 UTC",
  "2010-01-13 03:07:42 UTC",
  "2010-01-13 03:09:38 UTC",
  "2010-01-13 03:10:14 UTC",
  "2010-01-13 03:12:52 UTC",
  "2010-01-13 03:13:42 UTC",
  "2010-01-13 03:15:42 UTC",
  "2010-01-13 03:16:38 UTC",
  "2010-01-13 03:18:14 UTC",
  "2010-01-13 03:21:52 UTC",
  "2010-01-13 03:22:42 UTC",
  "2010-01-13 03:24:19 UTC",
  "2010-01-13 03:25:19 UTC"
)), x = cumsum(runif(15)*10),y=cumsum(runif(15)*20))


dlply(v,.(cut(datecol,"3 min")),"[")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...