【发布时间】:2021-11-11 21:58:45
【问题描述】:
我有一个问卷回复数据集,我想确定对一系列项目给出相同回复的受访者。使用 base::rle 我在新列表列中获得运行长度;我想提取每种情况的最大运行长度并将这些值添加为新列。
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.
由reprex package (v2.0.1) 于 2021-09-17 创建
【问题讨论】: