我有一个数据框,例如
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/