I have a dataset of responses to a questionnaire, and I want to identify respondents who give the same response to a series of items. Using base::rle I get run lengths in a new list column; I want to extract the maximum run length for each case and add these values as a new column.
library(tidyverse)
x <- tribble(
~x1, ~x2, ~x3, ~x4, ~x5, ~x6,
1, 1, 1, 1, 1, 1,
3, 3, 3, 2, 5, 3,
3, 3, 3, 3, 3, 3,
4, 4, 5, 5, 5, 5 )
# Add list col of runs
x <- x %>%
rowwise() %>%
mutate(runs = list(base::rle(c(x1, x2, x3, x4, x5, x6))))
# The list col is a list with 2 elements, 'lengths' and 'values'
str(x$runs[1])
#> List of 1
#> $ :List of 2
#> ..$ lengths: int 6
#> ..$ values : num 1
#> ..- attr(*, "class")= chr "rle"
# I can obtain max values of "lengths" for each row
map_int(map(x$runs, "lengths"), max)
#> [1] 6 3 6 4
# But I can't work out how to use 'mutate' to create a new variable containing
# the maximum for each case. I tried the following but it doesn't work.
x <- x %>%
rowwise() %>%
mutate(run_max = map_int(map(x$runs, "lengths"), max))
#> Error: Problem with `mutate()` column `run_max`.
#> i `run_max = map_int(map(x$runs, "lengths"), max)`.
#> i `run_max` must be size 1, not 4.
#> i Did you mean: `run_max = list(map_int(map(x$runs, "lengths"), max))` ?
#> i The error occurred in row 1.
Created on 2021-09-17 by the reprex package (v2.0.1)