- baby <- read.table("data.txt", sep = "\t", header = T)
- baby$action_time <- as.POSIXct(strptime(baby$action_time,
- "%Y-%m-%d %H:%M:%s"))
- sleep <- subset(baby, action_name %in% c("gnight", "gmorning"))
- # Trick to label each sleep period
- sleep$period <- cumsum(sleep$action_name == "gnight")
- # Now can easily use plyr
- library(plyr)
- # Remove cases that don't have exactly two observations
- sleep <- ddply(sleep, "period", function(df) {
- if (nrow(df) == 2) {
- df
- }
- })
- # This is the data format that's most useful for plotting. However, rather
- # than going through the gymnastics to get it into this format, I'd suggest
- # having a separate data frame for interval events where you record the
- # start and end of each event - i.e. just like this format
- asleep <- ddply(sleep, "period", summarise,
- start = action_time[action_name == "gnight"],
- end = action_time[action_name == "gmorning"]
- )
- asleep$length <- with(asleep, as.numeric(difftime(start, end,
- units = "mins")))
- library(ggplot2)
- print(qplot(start, length, data = asleep, geom = "line"))
- print(qplot(start, length / 60, data = asleep, ylab = "hours"))
- asleep$hour <- as.POSIXlt(asleep$start)$hour + 1
- qplot(hour, length / 60, data = asleep, geom = "boxplot", group = hour)
- ggsave(file = "ggplot2test.png")
- qplot(hour, length/60, data=asleep, alpha=I(1/10))
Posted by DK on Tue 3 Nov 02:24
report abuse | download | new post
Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.