r - 在行之间累积添加数字以在 R 中创建新列

标签 r dplyr tidyr

我有一个数据框,例如

Sp1 start end  
A   100   1077 
B   2316  4088
B   26647 28746
C   450    789
D   23     499
D   45999  60000

我想添加两个新列,我在其中累积添加以前的开始和结束坐标

首先,我应该始终为第一行获取相同的列:

Sp1 start end     new_start  new_end 
A   100   1077    100        1077

然后对于第一个 B :

Sp1 start end     new_start  new_end 
A   100   1077    100        1077
B   2316  4088    1078       2850
  • 其中 1078 = 1077 +1
  • 其中 2850 = 1078+(4088-2316)

对于另一个 B,它是名字:

Sp1 start end     new_start  new_end 
A   100   1077    100        1077
B   2316  4088    1078       2850
B   26647 28746   2851       4950
  • 其中 2851 = 2850 +1
  • 其中 4950 = 4951 +(28746-26647)

对于另一个 C,它是名称:

Sp1 start end     new_start  new_end 
A   100   1077    100        1077
B   2316  4088    1078       2850
B   26647 28746   2851       4950
C   450   789     4951       5290
  • 其中 4951 = 4950 +1
  • 其中 5290 = 4951 +(789-450)

然后在最后,我应该得到预期的结果:

Sp1 start end     new_start  new_end 
A   100   1077    100        1077
B   2316  4088    1078       2850
B   26647 28746   2851       4950
C   450   789     4951       5290

如果有人有想法,那就太棒了!

如果有帮助,这里是 dput 格式的数据帧:

structure(list(Sp1 = c("A", "B", "B", "C"), start = c(100L, 2316L, 
26647L, 450L), end = c(1077, 4088, 28746, 789)), class = "data.frame", row.names = c(NA, 
-4L))

最佳答案

如果您正在使用 tidyverse,您可以这样做...

df %>% mutate(new_end = start[1] - 1 + cumsum(end + 1) - cumsum(start),
              new_start = lag(new_end, default = start[1] - 1) + 1)

  Sp1 start   end new_end new_start
1   A   100  1077    1077       100
2   B  2316  4088    2850      1078
3   B 26647 28746    4950      2851
4   C   450   789    5290      4951
5   D    23   499    5767      5291
6   D 45999 60000   19769      5768

关于r - 在行之间累积添加数字以在 R 中创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73318736/

相关文章:

r - knitr hook 可以分隔 000,但不会持续多年

r - 识别两列之间的拼写错误

r - 了解 dplyr group_by 与 tapply 之间的结果差异

r - R 代码中 pivot_longer 函数的问题

r - 使用 data.table 的 X[Y] 语法在 R 中交错连接/新分组/连接

r - 将flexdashboard与多个页面不同类型的vertical_layout结合起来

r - 有什么方法可以仅使用 apply 函数将 Matrix 中的值替换为 NA

r - 在 R 中运行简单的 'rename' 函数时出现错误消息

r - 逐行嵌套所有列

r - 通过从另一个表中划分所有可能的列组合来创建新的数据框