【问题标题】:Repeat the rows in a data frame based on values in a specific column [duplicate]根据特定列中的值重复数据框中的行[重复]
【发布时间】:2016-11-24 17:44:31
【问题描述】:

我想根据samples 列在数据框中重复整行。

我的意见:

df <- 'chr start end samples
        1   10   20    2
        2   4    10    3'
df <- read.table(text=df, header=TRUE)

我的预期输出:

df <- 'chr start end  samples
        1   10   20   1-10-20-s1
        1   10   20   1-10-20-s2
        2   4    10   2-4-10-s1
        2   4    10   2-4-10-s2
        2   4    10   2-4-10-s3'

知道如何明智地执行它?

【问题讨论】:

  • 你可以使用df[rep(seq(nrow(df)), df$samples),]

标签: r repeat


【解决方案1】:

我们可以使用expandRows根据'samples'列中的值扩展行,然后转换为data.table,按'chr'分组,我们使用@987654323将列与行序列一起粘贴@ 更新“样本”列。

library(splitstackshape)
setDT(expandRows(df, "samples"))[,
     samples := sprintf("%d-%d-%d-%s%d", chr, start, end, "s",1:.N) , chr][]
#  chr start end    samples
#1:   1    10  20 1-10-20-s1
#2:   1    10  20 1-10-20-s2
#3:   2     4  10  2-4-10-s1
#4:   2     4  10  2-4-10-s2
#5:   2     4  10  2-4-10-s3

注意:data.table 将在我们加载 splitstackshape 时加载。

【讨论】:

    【解决方案2】:

    您可以使用 base R 来实现这一点(即避免使用 data.tables),代码如下:

    df <- 'chr start end samples
            1   10   20    2
            2   4    10    3'
    
    df <- read.table(text = df, header = TRUE)
    
    duplicate_rows <- function(chr, starts, ends, samples) {
      expanded_samples <- paste0(chr, "-", starts, "-", ends, "-", "s", 1:samples)
      repeated_rows <- data.frame("chr" = chr, "starts" = starts, "ends" = ends, "samples" = expanded_samples)
    
      repeated_rows
    }
    
    expanded_rows <- Map(f = duplicate_rows, df$chr, df$start, df$end, df$samples)
    
    new_df <- do.call(rbind, expanded_rows)
    

    基本思想是定义一个函数,该函数将从您的初始 data.frame 中获取一行,并根据 samples 列中的值复制行(以及创建您所追求的不同字符串) .然后将此函数应用于初始 data.frame 的每一行。输出是一个 data.frames 列表,然后需要使用 do.call 模式将其重新组合成单​​个 data.frame。

    上面的代码可以通过使用 Hadley Wickham 的 purrr 包(在 CRAN 上)和 data.frame 特定版本的 map(参见 by_row 函数的文档)变得更简洁,但这可能有点过头了为你所追求的。

    【讨论】:

      【解决方案3】:

      使用 S4Vector 包中的 DataFrame 函数的示例:

      df <- DataFrame(x=c('a', 'b', 'c', 'd', 'e'), y=1:5)
      rep(df, df$y)
      

      其中y列表示重复其对应行的次数。

      结果:

      DataFrame with 15 rows and 2 columns
                    x         y
          <character> <integer>
      1             a         1
      2             b         2
      3             b         2
      4             c         3
      5             c         3
      ...         ...       ...
      11            e         5
      12            e         5
      13            e         5
      14            e         5
      15            e         5
      

      【讨论】:

        猜你喜欢
        • 2021-12-06
        • 2018-04-02
        • 1970-01-01
        • 2021-05-04
        • 2020-12-08
        • 2021-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多