【问题标题】:Collapse rows across group and remove duplicates and NAs跨组折叠行并删除重复项和 NA
【发布时间】:2021-12-30 03:33:06
【问题描述】:

我想折叠组内各行的值并删除重复项和 NA。我尝试了几种{tidyverse} 方法,包括purrr::nestdplyr::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


    【解决方案1】:

    我们可以使用group_bysummarise(across(everything(), ...)) 将函数应用于每一列。在我们的例子中,这个函数被写成一个公式(~-notation),其中的列称为.x

    正如你所建议的,我们可以paste(和collapse = ", ")将这些行放在一起。我用.x[!is.na(.x)] 删除了NA 值。

    df_in %>% 
      group_by(group, subgroup) %>% 
      summarise(across(everything(), ~ paste(unique(.x[!is.na(.x)]), collapse = ", "))) %>% 
      ungroup()
    

    与预期输出的唯一区别是 shape 列现在是空字符串,而不是 NA 值:

    # A tibble: 1 x 6
      group subgroup color shape emotion    shade  
      <dbl> <chr>    <chr> <chr> <chr>      <chr>  
    1     1 a        red   ""    happy, sad striped
    

    这可以通过例如创建一个函数来解决,该函数在粘贴之前将零长度列表替换为NA

    paste_rows <- function(x) {
      unique_x <- unique(x[!is.na(x)])
      if (length(unique_x) == 0) {
        unique_x <- NA
      }
      
      paste(unique_x, collapse = ", ")
    }
    
    df_in %>% 
      group_by(group, subgroup) %>% 
      summarise(across(everything(), paste_rows)) %>% 
      ungroup()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-21
      • 2020-07-30
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多