使用两个不同的列在行之间进行变异

Mutate between rows using two different columns

我有这个 tbl/data.frame,其中包含基因名称、TSS(开始)和 GeneEnd(结束):

Genes       TSS GeneEnd
   <chr>     <int>   <int>
 1 homt-1     4221   10148
 2 nlp-40    11641   16585
 3 rcor-1    17911   26778
 4 sesn-1    28280   32482
 5 Y74C9A.1  43733   44677
 6 Y48G1C.12 47472   49416
 7 pgs-1     49921   54360
 8 Y48G1C.5  55337   63972
 9 csk-1     71425   80344
10 Y48G1C.10 81234   90607

我需要创建一个新列来计算基因的 TSS(start) 和前一个基因的 GeneEnd(End) 之间的差异。例如,对于 nlp-40,它将是 11641-10148。

这可能吗?

您可以使用 lag 来获取 GeneEnd 的先前值。

library(dplyr)
df <- df %>% mutate(diff = TSS - lag(GeneEnd))
df

#       Genes   TSS GeneEnd  diff
#1     homt-1  4221   10148    NA
#2     nlp-40 11641   16585  1493
#3     rcor-1 17911   26778  1326
#4     sesn-1 28280   32482  1502
#5   Y74C9A.1 43733   44677 11251
#6  Y48G1C.12 47472   49416  2795
#7      pgs-1 49921   54360   505
#8   Y48G1C.5 55337   63972   977
#9      csk-1 71425   80344  7453
#10 Y48G1C.10 81234   90607   890

这也可以在 base R 和 data.table -

中实现
#data.table
library(data.table)
setDT(df)[, diff := TSS - shift(GeneEnd)]

#Base R
transform(df, diff = TSS - c(NA, GeneEnd[-nrow(df)]))