R Optimizing double for loop, matrix manipulation

后端 未结 4 2085
感情败类
感情败类 2021-01-20 19:20

I am trying to manipulate column data in a two column matrix and output it as a data.frame.

The matrix that I have is in this format where both the values in the sta

4条回答
  •  无人及你
    2021-01-20 20:09

    Here is a simple base R version

    with(as.data.frame(dat), {
      data.frame(
        Start=tapply(Start, cut(Start, c(0, End)), c),
        End=na.omit(End)
      )
    })
    #        Start End
    # 1    1, 2, 3   6
    # 2       7, 8   9
    # 3 11, 12, 14  15
    

    Another

    with(as.data.frame(dat), {
      group <- as.integer(cut(Start, c(0, End)))                  # assign Start values to End groups
      data.frame(
        Start=unclass(by(dat, group, function(g) g[["Start"]])),  # combine Start groups
        End=unique(na.omit(End))                                  # Remove duplicate/NA End values
      )
    })
    

提交回复
热议问题