【发布时间】:2021-12-30 03:33:06
【问题描述】:
我想折叠组内各行的值并删除重复项和 NA。我尝试了几种{tidyverse} 方法,包括purrr::nest、dplyr::summarize(x = paste(x, collapse = ", ") and dplyr::summarize(x = list(x)`,但都没有成功。我将不胜感激!输入和所需的输出如下。
# Collapse rows across group and remove duplicates and NAs
library(dplyr)
df_in <- tribble(
~group, ~subgroup, ~color, ~shape, ~emotion, ~shade,
1, "a", "red", NA, "happy", NA,
1, "a", "red", NA, "sad", "striped"
)
df_in
#> # A tibble: 2 × 6
#> group subgroup color shape emotion shade
#> <dbl> <chr> <chr> <lgl> <chr> <chr>
#> 1 1 a red NA happy <NA>
#> 2 1 a red NA sad striped
df_out <- tribble(
~group, ~subgroup, ~color, ~shape, ~emotion, ~shade,
1, "a", "red", NA, "happy, sad", "striped"
)
df_out
#> # A tibble: 1 × 6
#> group subgroup color shape emotion shade
#> <dbl> <chr> <chr> <lgl> <chr> <chr>
#> 1 1 a red NA happy, sad striped
由reprex package (v2.0.0) 于 2021 年 11 月 19 日创建
【问题讨论】:
标签: r dplyr tidyverse nest summarize