簡體   English   中英

跨列取消嵌套字符串組,但將它們保留在 R 的原始行中

[英]Unnest group of string across columns but keep them in the original row in R

我正在嘗試找到一種方法來取消跨列的字符串組,但將所有字符串保留在原始行中。 dplyr中的示例數據集starwars為例,因為它與我的數據集具有相似的結構。

starwars數據集有 3 個嵌套列,分別是filmsvehiclesstarships 常見的方法是做一個unnest_longer ,所以我們將字符串組取消嵌套到多行中 - 每行包含一個字符串。 但是,我更願意將所有未分組的字符串保留在原始行中。

另一種方法是使用rowwise()並使用paste進行mutate 這可行,但我的數據集有 15 個嵌套列,所以我必須輸入 15 行 mutate 和粘貼。 這有點乏味。

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

我目前的想法是想出一個包裝 function ,也許我可以通過大規模的purrr來做到這一點。 但是我可憐的 function 寫作不起作用 - 也許我對 dplyr 引擎蓋不太熟悉。

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

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

您可以使用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 列中的每一列。 您可以通過 position 1:15 、范圍col1:col15或名稱中的某些模式來命名 select 列名starts_with('col')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM