I have a data.frame
containing information from a website log. Among other columns the data.frame
contains the cookie ID, the timestamp and the URL. Now I want to compute the time spent on each page, assuming that a page is viewed until another page is loaded by the same cookie ID. This is why the data.frame
is ordered by cookie ID and timestamp using:
data = data[with(data, order(cookie_id, timestamp)), ]
Here is how I calculate the time spent on each page using a for
loop:
data$calc_time_spent = NA
for (i in 1:(nrow(data)-1)) {
if (!is.na(data$cookie_id[i]) & !is.na(data$cookie_id[i+1]) & data$cookie_id[i] == data$cookie_id[i+1]) {
data$calc_time_spent[i] = data$timestamp[i+1]-data$timestamp[i]
}
}
Unfortunately this is very slow, so I need a more sophisticated solution, maybe using the apply-function?
-
Here are some example data:
cookie_id = c("5", "5", "8", "8", "8")
timestamp = as.POSIXlt(c("2005-4-19 7:01:33", "2005-4-19 7:01:35", "2005-4-19 7:01:10", "2005-4-19 7:01:23", "2005-4-19 7:01:27"))
data = data.frame(timestamp, cookie_id)
Which look like this:
timestamp cookie_id
1 2005-04-19 07:01:33 5
2 2005-04-19 07:01:35 5
3 2005-04-19 07:01:10 8
4 2005-04-19 07:01:23 8
5 2005-04-19 07:01:27 8
After the operation the data should have a third column:
timestamp cookie_id calc_time_spent
1 2005-04-19 07:01:33 5 2
2 2005-04-19 07:01:35 5 NA
3 2005-04-19 07:01:10 8 13
4 2005-04-19 07:01:23 8 4
5 2005-04-19 07:01:27 8 NA