I'm trying to use dplyr to insert run lengths of column value into my data for each group.
tdf <- tbl_df(structure(list(group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("A",
"B"), class = "factor"), value = c(TRUE, TRUE, TRUE, TRUE, TRUE,
TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, TRUE, TRUE, FALSE, FALSE, FALSE)), class = c("tbl_df",
"tbl", "data.frame"), .Names = c("group", "value"), row.names = c(NA,
-20L)))
My data looks like this...
> tdf
Source: local data frame [20 x 2]
group value
1 A TRUE
2 A TRUE
3 A TRUE
4 A TRUE
5 A TRUE
6 A TRUE
7 A FALSE
8 A FALSE
9 A TRUE
10 A FALSE
11 B FALSE
12 B FALSE
13 B FALSE
14 B FALSE
15 B FALSE
16 B TRUE
17 B TRUE
18 B FALSE
19 B FALSE
20 B FALSE
And my desired output looks like this... (notice that the run lengths restart between groups)
group value run_length
1 A TRUE 6
2 A TRUE 6
3 A TRUE 6
4 A TRUE 6
5 A TRUE 6
6 A TRUE 6
7 A FALSE 2
8 A FALSE 2
9 A TRUE 1
10 A FALSE 1
11 B FALSE 5
12 B FALSE 5
13 B FALSE 5
14 B FALSE 5
15 B FALSE 5
16 B TRUE 2
17 B TRUE 2
18 B FALSE 3
19 B FALSE 3
20 B FALSE 3
I figured it would just be a matter of doing this in dplyr...
group_by(tdf, group) %.%
mutate(run_len = rep(rle(value)$lengths,rle(value)$lengths))
But I get the error:
Error in rle(value) : object 'value' not found
I have a solution outside of dplyr using split and lapply, but would like to know how this would work in dplyr.
dplyr. I suspect you might haveplyrloaded as well which is messing upmutate. - Ramnath