【问题标题】:"Undoing" a nested tibble created with stringr::str_split“撤消”使用 stringr::str_split 创建的嵌套 tibble
【发布时间】:2019-06-02 19:02:46
【问题描述】:

我使用stringr::str_split 在 R 中创建了一个嵌套的 tibble。有没有比我在下面提出的解决方案更优雅的方式从嵌套的 tibble 到“原始”tibble?

library(tidyverse)
# original tibble
df <- tibble(x = c("a", "b"),
             y = c("a1, a2", "b1, b2"))
df
#> # A tibble: 2 x 2
#>   x     y     
#>   <chr> <chr> 
#> 1 a     a1, a2
#> 2 b     b1, b2

# nested version
df_nested <- df %>% 
  mutate(y = str_split(y, ", "))
df_nested
#> # A tibble: 2 x 2
#>   x     y        
#>   <chr> <list>   
#> 1 a     <chr [2]>
#> 2 b     <chr [2]>

# to get back to original
mutate(df, y = unlist(lapply(y, paste0, collapse = ", ")))
#> # A tibble: 2 x 2
#>   x     y     
#>   <chr> <chr> 
#> 1 a     a1, a2
#> 2 b     b1, b2

reprex package (v0.2.1) 于 2019-01-07 创建

【问题讨论】:

    标签: r tidyr stringr


    【解决方案1】:

    我们可以从purrr使用map

    library(tidyverse)
    df_nested %>% 
         mutate(y = map_chr(y, toString))
    # A tibble: 2 x 2
    #  x     y     
    #  <chr> <chr> 
    #1 a     a1, a2
    #2 b     b1, b2
    

    另外,这两个步骤都可以使用tidyverse 以另一种方式使用separate_rowsgroup_bysummarise 完成

    df %>% 
      separate_rows(y) %>% # long format
      group_by(x) %>% 
      summarise(y = toString(y)) # wide format
    

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 2011-06-18
      • 1970-01-01
      • 2021-04-25
      • 2019-08-07
      • 2020-12-08
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      相关资源
      最近更新 更多