R-Help
I have a data set which uses a DateTime string as follows : "2009-06-30
18:14:59"
While I have been able to convert to DateTime properly
time <- strptime(as.character(dat$Time),format='%d %b %Y %T') #Convert to
dateTime string
I would like to use the time of day "hour" as a *factor* level. I have
found that I can convert the date time to a factor
time <- as.ordered(cut(time, "hour"))
But this produces a factor level for every single day. The issue I have is
in figuring out how to apply a logical statement to the datetime string or
to the factor. I would like to say that every datetime with an hour <12 is
the morning factor, and every datetime with an hour >12 is at night. Without
LOTS of superfluous code. below I am going as far as splitting the string
to columns, pulling the time and then setting the factor with a for
statement...yeesh. I have example CSV dates at the end.
new.dates <- matrix(unlist(lapply(as.character(dat$Time), function(x)
strsplit(x," "))),ncol=4, byrow=TRUE) #Break Time String into columns
colnames(new.dates) <- c("day","month","year", "time") # Set column names
dat <- cbind(as.data.frame(new.dates), as.data.frame(dat)) #bind to data
frame
tfact<-matrix()
for (i in which(as.character(dat$time) <= "12:00:00")){
tfact[i] <- "Morning"
}
for (i in which(as.character(dat$time) >= "12:00:00")){
tfact[i] <- "Night"
}
tfact<-factor(tfact,
levels=c("Morning", "Night"),
)
Example CSV Data
"1","30 Jun 2009 18:14:59"
"2","02 Jul 2009 07:33:37"
"3","06 Jul 2009 08:22:35"
"4","06 Jul 2009 19:25:50"
"5","08 Jul 2009 08:41:48"
"6","10 Jul 2009 07:31:39"
"7","10 Jul 2009 19:59:25"
"8","13 Jul 2009 07:49:18"
"9","13 Jul 2009 18:52:52"
"10","15 Jul 2009 08:06:56"
"11","15 Jul 2009 19:03:01"
"12","17 Jul 2009 08:02:02"
Thanks
Pat
--
Patrick Schmitz
Graduate Student
Plant Biology
1206 West Gregory Drive
RM 1500
[[alternative HTML version deleted]]
______________________________________________
[email protected] 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.