将分裂区间坐标转换为连续区间坐标。

4

我有一个data.frame,其中每个id映射到多个不连续的线性区间,这些区间不重叠,并按升序排序:

df <- data.frame(id = c(rep("id1",3),rep("id2",4)),
                 start = c(101,220,307,550,658,742,855),
                 end = c(154,246,326,625,712,811,944),
                 stringsAsFactors = F)

我想添加新的“start”和“end”列,这些列将累加间隔宽度并显示累积的起始和结束坐标。
因此,对于上面的示例“df”,这些新的“start”和“end”列(“cum.start”,“cum.end”)将是:
df$cum.start <- c(1,55,82,1,77,132,202)
df$cum.end <- c(54,81,101,76,131,201,291)

有没有使用dplyr的方法来实现这个?

2个回答

2
我们可以使用lagcumsum:
library(dplyr)

df1 %>% 
  group_by(id) %>% 
  mutate(cum.start = c(1, lag(cumsum(end - start + 1))[-1] + 1) ,
         cum.end = cumsum(end - start + 1))

#> # A tibble: 7 x 5
#> # Groups:   id [2]
#>   id    start   end cum.start cum.end
#>   <chr> <dbl> <dbl>     <dbl>   <dbl>
#> 1 id1     101   154         1      54
#> 2 id1     220   246        55      81
#> 3 id1     307   326        82     101
#> 4 id2     550   625         1      76
#> 5 id2     658   712        77     131
#> 6 id2     742   811       132     201
#> 7 id2     855   944       202     291

2
我认为每个人都有类似的想法,所以我不会再发表另一个答案。变化 - df%>%按id分组%>% mutate(newend = cumsum(end-start + 1),newstart = lag(newend + 1,默认值= 1)) - thelatemail
1
@thelatemail 我一开始也是这样做的,但觉得重新排列列可能更有效。 - M--

2
请看下面使用 dplyr 的一种可能解决方案:
  • 代码
df %>% 
  group_by(id) %>% 
  mutate( diff = end-start+1,
               cum.end = cumsum(diff),
               cum.start = cum.end - diff + 1) %>% 
  select(-diff) %>% 
  relocate("cum.end", .after = last_col())
  • Output
#> # A tibble: 7 x 5
#> # Groups:   id [2]
#>   id    start   end cum.start cum.end
#>   <chr> <dbl> <dbl>     <dbl>   <dbl>
#> 1 id1     101   154         1      54
#> 2 id1     220   246        55      81
#> 3 id1     307   326        82     101
#> 4 id2     550   625         1      76
#> 5 id2     658   712        77     131
#> 6 id2     742   811       132     201
#> 7 id2     855   944       202     291

创建于2021年12月15日,使用reprex包(v2.0.1)


2
你需要使用group_by(id) - M--

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接