【问题标题】:How to Split a dataframe column that is a dictionary into two columns如何将作为字典的数据框列拆分为两列
【发布时间】:2021-10-13 16:31:05
【问题描述】:

我有一个包含一列的数据框,例如

ID dictionary_column
1 {1:5, 10:15, 3:9}
2 {3:4, 5:3}
... ...

我试图让它看起来像:

ID col_a col_b
1 1 5
1 10 15
1 3 9
2 3 4
2 5 3
... ... ...

对此有何建议?使用stringr 使用了各种方法,但总是忘记 ID 列或以混乱和缓慢的循环结束。谢谢

【问题讨论】:

  • 请通过粘贴来自dput(your_dataframe) 的输出来提供可重现的数据。

标签: r data-manipulation


【解决方案1】:

实现所需结果的tidyverse 方法可能如下所示:

library(dplyr)
library(tidyr)

data.frame(
  ID = c(1L, 2L),
  dictionary_column = c("{1:5, 10:15, 3:9}", "{3:4, 5:3}")
) %>%
  mutate(dictionary_column = gsub("(\\{|\\})", "", dictionary_column)) %>%
  separate_rows(dictionary_column, sep = ", ") %>%
  separate(dictionary_column, into = c("col_a", "col_b"))
#> # A tibble: 5 × 3
#>      ID col_a col_b
#>   <int> <chr> <chr>
#> 1     1 1     5    
#> 2     1 10    15   
#> 3     1 3     9    
#> 4     2 3     4    
#> 5     2 5     3

【讨论】:

    【解决方案2】:

    带有str_extract_all 的选项可将: 前后的数字提取到list 列中,然后将unnest 提取到list 中

    library(stringr)
    library(dplyr)
    library(tidyr)
    df1 %>%
        mutate(col_a = str_extract_all(dictionary_column, "\\d+(?=:)"),
           col_b = str_extract_all(dictionary_column, "(?<=:)\\d+"), 
           .keep = "unused") %>% 
        unnest(c(col_a, col_b))
    

    -输出

    # A tibble: 5 × 3
         ID col_a col_b
      <int> <chr> <chr>
    1     1 1     5    
    2     1 10    15   
    3     1 3     9    
    4     2 3     4    
    5     2 5     3   
    

    数据

    df1 <- structure(list(ID = 1:2, dictionary_column = c("{1:5, 10:15, 3:9}", 
    "{3:4, 5:3}")), class = "data.frame", row.names = c(NA, -2L))
    

    【讨论】:

      【解决方案3】:

      不是很优雅,但很有效:

      library(tidyr)
      library(dplyr)
      
      dat %>% 
        mutate(dictionary_column = gsub("\\{|\\}|\\,", "", dictionary_column)) %>% 
        separate(dictionary_column, into=c("a", "b", "c"), sep=" ") %>% 
        pivot_longer(-ID, values_drop_na=T) %>% 
        select(-name) %>% 
        separate(value, into = c("col_a", "col_b"))
      
      # A tibble: 5 × 3
           ID col_a col_b
        <int> <chr> <chr>
      1     1 1     5    
      2     1 10    15   
      3     1 3     9    
      4     2 3     4    
      5     2 5     3    
      

      【讨论】:

        猜你喜欢
        • 2022-01-20
        • 2013-01-22
        相关资源
        最近更新 更多