首页 > 解决方案 > 跨列取消嵌套字符串组,但将它们保留在 R 中的原始行中

问题描述

我正在尝试找到一种方法来取消跨列的字符串组,但将所有字符串保留在原始行中。从中获取示例数据集starwarsdplyr因为它与我的数据集具有相似的结构。

数据集starwars有 3 个嵌套列films, vehicles, starships。常见的方法是这样做,unnest_longer因此我们将字符串组取消嵌套为多行 - 每行包含一个字符串。但是,我更愿意将所有未分组的字符串保留在原始行中。

另一种方法是使用rowwise()and mutatewith paste。这可行,但我的数据集有 15 个嵌套列,所以我必须输入 15 行 mutate 和粘贴。这有点乏味。

df <- dplyr::starwars %>%
  rowwise() %>%
  mutate(films = paste(films, collapse=', '),
         vehicles = paste(vehicles, collapse=', '),
         starships = paste(starships, collapse=', '))

我目前的想法是想出一个包装函数,也许我可以purrr大规模地完成它。但是我糟糕的函数编写不起作用 - 也许我对 dplyr 引擎盖不太熟悉。

ungroup_string <- function(data, x){
  a <- rowwise(data)
  a %>% mutate(x = paste(x, collapse=','))
}

有什么办法可以跨多列取消组合字符串?

标签: rfunctionpurrrdplyr

解决方案


您可以使用across

library(dplyr)

starwars %>%
  select(name, films, vehicles, starships) %>%
  rowwise() %>%
  mutate(across(c(films,vehicles, starships), toString))

#    name       films                                vehicles         starships                             
#   <chr>      <chr>                                <chr>            <chr>                                 
# 1 Luke Skyw… The Empire Strikes Back, Revenge of… "Snowspeeder, I… "X-wing, Imperial shuttle"            
# 2 C-3PO      The Empire Strikes Back, Attack of … ""               ""                                    
# 3 R2-D2      The Empire Strikes Back, Attack of … ""               ""                                    
# 4 Darth Vad… The Empire Strikes Back, Revenge of… ""               "TIE Advanced x1"                     
# 5 Leia Orga… The Empire Strikes Back, Revenge of… "Imperial Speed… ""                                    
# 6 Owen Lars  Attack of the Clones, Revenge of th… ""               ""                                    
# 7 Beru Whit… Attack of the Clones, Revenge of th… ""               ""                                    
# 8 R5-D4      A New Hope                           ""               ""                                    
# 9 Biggs Dar… A New Hope                           ""               "X-wing"                              
#10 Obi-Wan K… The Empire Strikes Back, Attack of … "Tribubble bong… "Jedi starfighter, Trade Federation c…
# … with 77 more rows

across接受 tidy-select 变量。因此,您不必一一指定 15 列中的每一列。您可以按位置1:15、范围col1:col15或名称中的某些模式选择列名称starts_with('col')


推荐阅读