I cannot find a satisfying tutorial that would explain me how to use all the possibilities of apply functions. I'm still a newbie but this could often come in handy and significantly simplify my code. So here's my example... I've got a data frame which looks like this:
> head(p01)
time key dwell
1 8.13 z 0.00
3 8.13 x 1.25
5 9.38 l 0.87
7 10.25 x 0.15
9 10.40 l 1.13
11 11.53 x 0.45
get it into R:
p01 <- structure(list(time = c(8.13, 8.13, 9.38, 10.25, 10.4, 11.53),
key = c("z", "x", "l", "x", "l", "x"), dwell = c(0, 1.25,
0.869, 0.15, 1.13, 0.45)), .Names = c("time", "key", "dwell"), row.names = c(1L, 3L, 5L, 7L, 9L, 11L), class = "data.frame")
Now I want to count the occurences of each letter in p01$key
and print them in p01$occurences
, so that the result would look like this:
time key dwell occurences
1 8.13 z 0.00 1
3 8.13 x 1.25 3
5 9.38 l 0.87 2
7 10.25 x 0.15 3
9 10.40 l 1.13 2
11 11.53 x 0.45 3
The way I do it now is:
p01[p01$key == "l", "occurences"] <- table(p01$key)["l"]
p01[p01$key == "x", "occurences"] <- table(p01$key)["x"]
p01[p01$key == "z", "occurences"] <- table(p01$key)["z"]
...which of course is not the best solution. Especially since the real data contains more possibilities in p01$key
(one of 16 different letters).
On top of that I want to calculate total dwell
for each letter, so what I'm doing now is:
p01[p01$key == "l", "total_dwell"] <- tapply(p01$dwell, p01$key, sum)["l"]
p01[p01$key == "x", "total_dwell"] <- tapply(p01$dwell, p01$key, sum)["x"]
p01[p01$key == "z", "total_dwell"] <- tapply(p01$dwell, p01$key, sum)["z"]
in order to get:
time key dwell total_dwell
1 8.13 z 0.00 0.00
3 8.13 x 1.25 1.85
5 9.38 l 0.87 2.00
7 10.25 x 0.15 1.85
9 10.40 l 1.13 2.00
11 11.53 x 0.45 1.85
I've been googling and going through couple of books for the last 6 hours. Will really appreciate an elegant solution and/or a link to some comprehansive tutorial. My solution is obviously working, but it's not the first time I have to go around the problem like this and my script files are starting to look ridiculous!