[R] Assign date according to defined time interval
arun
smartpink111 at yahoo.com
Wed Oct 16 02:00:01 CEST 2013
Hi,
Please use ?dput() to show the dataset. Also, it is not clear about how you store the time interval.
dat <- read.table(text="
GroupID Date
1 1 10-Dec-12
2 1 11-Dec-12
3 2 13-Dec-12
4 2 15-Dec-12
5 3 06-Dec-12
6 3 19-Dec-12",sep="",header=TRUE,stringsAsFactors=FALSE)
dat2 <- data.frame(Week=1:2, from= c("9-Dec-12", "16-Dec-12"), to=c("15-Dec-12","22-Dec-12"),stringsAsFactors=FALSE)
#Check ?findInterval()
res <- t(sapply(split(dat,dat$GroupID), function(x) {
x$Date <-as.Date(x$Date,"%d-%b-%y")
unsplit(lapply(split(dat2,dat2$Week),function(y) {
y$from <- as.Date(y$from, "%d-%b-%y")
y$to <- as.Date(y$to, "%d-%b-%y")
sum(x$Date > y$from & x$Date <= y$to)}),
dat2$Week)
}))
colnames(res) <- paste0("Week",1:2)
res
# Week1 Week2
#1 2 0
#2 2 0
#3 0 1
A.K.
On Tuesday, October 15, 2013 6:24 PM, Weijia Wang <zeleehom at gmail.com> wrote:
Hi, I have something very interesting:
Say I have this:
GroupID Date
1 1 10-Dec-12
2 1 11-Dec-12
3 2 13-Dec-12
4 2 15-Dec-12
5 3 06-Dec-12
6 3 19-Dec-12
Now, I have time interval,
week 1: from 9-Dec-12 to 15-Dec-12,
week 2: from 16-Dec-12 to 22-Dec-12, and so on.
Obviously, the 1st, 2nd, 3rd, 4th row falls to week 1, 5th rows should not
be counted, 6th row falls into week2.
Therefore, by GroupID, I will have
GroupID=1, Week1=2, Week2=0
GroupID=2, Week1=2, Week2=0
GroupID=3, Week1=0, Week2=1.
I just want to count the valid date that falls into a 7-day week interval,
and I shall have new variables for EACH WEEK, and the counts for dates that
fall into this week interval.
Can anyone please help me on programming this?
W
[[alternative HTML version deleted]]
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list