【问题标题】:splitting a string in a column and adding duplicate rows in R在列中拆分字符串并在 R 中添加重复的行
【发布时间】:2018-11-01 00:16:00
【问题描述】:

假设我有以下数据框,称为“示例”:

a <- c("rs123|rs246|rs689653", "rs9753", "rs00334")
b <- c(1,2,9)
c <- c(234534523, 67345634, 536423)

example <- data.frame(a,b,c)

我希望数据框看起来像这样:

                a b         c
            rs123 1 234534523
            rs246 1 234534523
         rs689653 1 234534523
           rs9753 2  67345634
          rs00334 9    536423

如果我们在 | 分隔符上拆分列 a,则其他列会重复。任何帮助将不胜感激!

【问题讨论】:

    标签: r dataframe split


    【解决方案1】:

    我们可以使用tidyr 包中的separate_rowstidyverse 包的一部分)。

    library(tidyverse)
    
    example2 <- example %>%
      separate_rows(a)
    example2
    #          a b         c
    # 1    rs123 1 234534523
    # 2    rs246 1 234534523
    # 3 rs689653 1 234534523
    # 4   rs9753 2  67345634
    # 5  rs00334 9    536423
    

    这是将example2 转换回原始格式的一种方法。

    example3 <- example2 %>%
      group_by(b, c) %>%
      summarize(a = str_c(a, collapse = "|")) %>%
      ungroup() %>%
      select(names(example2)) %>%
      mutate(a = factor(a)) %>%
      as.data.frame()
    
    identical(example, example3)
    # [1] TRUE
    

    【讨论】:

    • 谢谢!只是为了完整性和好奇心的销售,假设我想从'example2'回到'example'之类的东西。最好的方法是什么?
    猜你喜欢
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    相关资源
    最近更新 更多