[英]how to calculate gaps between two columns in r
I'm looking to calculate the gaps between a previous "end" number, with the next "start" number.我正在计算前一个“结束”数字与下一个“开始”数字之间的差距。 Referring to the data attached, as an example, the result is in df$gap.参考附上的数据,作为例子,结果在df$gap中。 In the first row, the number is df$gap=df$start[1]-1.在第一行,数字是 df$gap=df$start[1]-1。 the rest of result would be df$start[n]-df$end[n-1].其余的结果将是 df$start[n]-df$end[n-1]。 I can easily do this in Excel, however, I am having difficulty with figuring out how to do this in R without loop.我可以在 Excel 中轻松地做到这一点,但是,我很难弄清楚如何在没有循环的情况下在 R 中做到这一点。
If anyone could provide a solution, that would be much appreciated!如果有人可以提供解决方案,那将不胜感激!
df = read.table(text="start end
172 635
766 1699
1817 1891
2015 2320", header=T)
the expected result:预期结果:
start end gap
172 635 171
766 1699 131
1817 1891 118
2015 2320 124
Using dplyr
this is a solution using lag
使用dplyr
这是使用lag
的解决方案
df %>% mutate(gap = start - lag(end))%>%
mutate(gap = ifelse(row_number() == 1,start -1,gap))
Output:输出:
start end gap
1 172 635 171
2 766 1699 131
3 1817 1891 118
4 2015 2320 124
In base R:在基础 R 中:
df$gap <- df$start - c(1L, head(df$end, -1))
Gives:给出:
df
start end gap
1 172 635 171
2 766 1699 131
3 1817 1891 118
4 2015 2320 124
If I get your question, one solution could be lag
function from dplyr
如果我得到你的问题,一个解决方案可能是dplyr
lag
函数
For istance:例如:
df[,'gap'] = df[,'start'] - lag(df[,"end"], n = 1)
dplyr
plus a small trick could help with that: dplyr
加上一个小技巧可以帮助解决这个问题:
library(dplyr)
df = read.table(text="start end
172 635
766 1699
1817 1891
2015 2320", header=T)
df$temp <- c(1, df$end[-length(df$end)])
mutate(df, gap = start - temp) |> select(-temp)
Output:输出:
start end gap
1 172 635 171
2 766 1699 131
3 1817 1891 118
4 2015 2320 124
One possible solution with the package data.table
包data.table
一种可能的解决方案
Please find the reprex below.请在下面找到reprex。
REPREX REPREX
library(data.table)
DT <- setDT(df)
DT[, end_lead := shift(end,1)][, `:=` (gap = start - end_lead, end_lead = NULL)]
setnafill(DT, fill = DT$start[1] - 1)
DT
#> start end gap
#> 1: 172 635 171
#> 2: 766 1699 131
#> 3: 1817 1891 118
#> 4: 2015 2320 124
Created on 2021-10-13 by the reprex package (v0.3.0)由reprex 包(v0.3.0) 于 2021 年 10 月 13 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.