压缩/汇总R中的字符串起始和长度数据

问题描述 投票:0回答:1

我在较大的字符串中有data.frame个(子)字符串位置。数据包含(子)字符串的开始及其长度。 (子)字符串的结束位置很容易计算。

data1 <- data.frame(start = c(1,3,4,9,10,13),
                   length = c(2,1,3,1,2,1)
                   )

data1$end <- (data1$start + data1$length - 1)

data1
#>   start length end
#> 1     1      2   2
#> 2     3      1   3
#> 3     4      3   6
#> 4     9      1   9
#> 5    10      2  11
#> 6    13      1  13

reprex package(v0.3.0)在2019-12-10创建

我想通过总结连续的(子)字符串(相互连接的字符串)来'压缩'此data.frame,以便我的新数据看起来像这样:

data2 <- data.frame(start = c(1,9,13),
                   length = c(6,3,1)
                   )

data2$end <- (data2$start + data2$length - 1)

data2
#>   start length end
#> 1     1      6   6
#> 2     9      3  11
#> 3    13      1  13

reprex package(v0.3.0)在2019-12-10创建

[最好是有一个将我从data1转移到data2的基R解?

r string
1个回答
1
投票

使用dplyr,我们可以执行以下操作:

library(dplyr)

data1 %>% 
  group_by(consecutive = cumsum(start != lag(end, default = 0) + 1)) %>% 
  summarise(start = min(start), length=sum(length), end=max(end)) %>% 
  ungroup %>% select(-consecutive)

#> # A tibble: 3 x 3
#>   start length   end
#>   <dbl>  <dbl> <dbl>
#> 1     1      6     6
#> 2     9      3    11
#> 3    13      1    13
© www.soinside.com 2019 - 2024. All rights reserved.