[英]how to calculate gaps between two columns in r
我正在計算前一個“結束”數字與下一個“開始”數字之間的差距。 參考附上的數據,作為例子,結果在df$gap中。 在第一行,數字是 df$gap=df$start[1]-1。 其余的結果將是 df$start[n]-df$end[n-1]。 我可以在 Excel 中輕松地做到這一點,但是,我很難弄清楚如何在沒有循環的情況下在 R 中做到這一點。
如果有人可以提供解決方案,那將不勝感激!
df = read.table(text="start end
172 635
766 1699
1817 1891
2015 2320", header=T)
預期結果:
start end gap
172 635 171
766 1699 131
1817 1891 118
2015 2320 124
使用dplyr
這是使用lag
的解決方案
df %>% mutate(gap = start - lag(end))%>%
mutate(gap = ifelse(row_number() == 1,start -1,gap))
輸出:
start end gap
1 172 635 171
2 766 1699 131
3 1817 1891 118
4 2015 2320 124
在基礎 R 中:
df$gap <- df$start - c(1L, head(df$end, -1))
給出:
df
start end gap
1 172 635 171
2 766 1699 131
3 1817 1891 118
4 2015 2320 124
如果我得到你的問題,一個解決方案可能是dplyr
lag
函數
例如:
df[,'gap'] = df[,'start'] - lag(df[,"end"], n = 1)
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)
輸出:
start end gap
1 172 635 171
2 766 1699 131
3 1817 1891 118
4 2015 2320 124
包data.table
一種可能的解決方案
請在下面找到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
由reprex 包(v0.3.0) 於 2021 年 10 月 13 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.