在 R 中,使用一个日期列如何从当前行中减去上面的 2 个点并在新列中添加结果?
In R, using one date column how do i subtract 2 spots above from the current line and in a new column add the result?
我有一个日期栏,我只想使用这一栏中的信息
Date
2020-01-05
2020-01-30
2020-01-20
2020-01-10
2020-01-15
2020-01-30
我新建了一个专栏
dfto1_difference
我想创建的函数给了我这个结果。我想让第三列减去第一列
Date | 3to1_difference
2020-01-05 N/A
2020-01-30 N/A
2020-01-20 15
2020-01-10 -20
2020-01-15 -5
2020-01-30 20
library(lubridate)
library(tibble)
library(dplyr)
tbl <- tibble::tibble(date = lubridate::as_date( c("2020-01-05", "2020-01-30","2020-01-20", "2020-01-10", "2020-01-15", "2020-01-30")))
tbl %>% mutate(`3to1difference` = date - lag(date, n = 2)) ## as difference in days
tbl %>% mutate(`3to1difference` = as.numeric(date - lag(date, n = 2))) ## as numeric variable
选项data.table
library(data.table)
setDT(tbl)[, `3toldifference` := .(date = shift(date, n = 3))]
我有一个日期栏,我只想使用这一栏中的信息
Date
2020-01-05
2020-01-30
2020-01-20
2020-01-10
2020-01-15
2020-01-30
我新建了一个专栏
dfto1_difference
我想创建的函数给了我这个结果。我想让第三列减去第一列
Date | 3to1_difference
2020-01-05 N/A
2020-01-30 N/A
2020-01-20 15
2020-01-10 -20
2020-01-15 -5
2020-01-30 20
library(lubridate)
library(tibble)
library(dplyr)
tbl <- tibble::tibble(date = lubridate::as_date( c("2020-01-05", "2020-01-30","2020-01-20", "2020-01-10", "2020-01-15", "2020-01-30")))
tbl %>% mutate(`3to1difference` = date - lag(date, n = 2)) ## as difference in days
tbl %>% mutate(`3to1difference` = as.numeric(date - lag(date, n = 2))) ## as numeric variable
选项data.table
library(data.table)
setDT(tbl)[, `3toldifference` := .(date = shift(date, n = 3))]