tlead-tlag: lead and lag with respect to a time variable

Description Usage Arguments Examples

Description

lead and lag with respect to a time variable

Usage

1
2
3
tlead(x, n = 1L, time, default = NA)

tlag(x, n = 1L, time, default = NA)

Arguments

x

a vector of values

n

a positive integer of length 1, giving the number of positions to lead or lag by. When the package lubridate is loaded, it can be a period when using with time (see the lubridate function minutes, hours, days, weeks, months and years)

time

time variable

default

value used for non-existant rows. Defaults to NA.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
date <- c(1989, 1991, 1992)
value <- c(4.1, 4.5, 3.3)
tlag(value, 1, time = date) #  returns value in year - 1
library(lubridate)
date <- as.monthly(mdy(c("01/04/1992", "03/15/1992", "04/03/1992")))
tlag(value, time = date) 
library(dplyr)
df <- tibble(
   id    = c(1, 2, 2),
   date  = date,
   value = value
)
df %>% group_by(id) %>% mutate(valuel = tlag(value, n = 1, time = date))

Example output

[1]  NA  NA 4.5

Attaching package: 'lubridate'

The following object is masked from 'package:base':

    date

[1]  NA  NA 4.5

Attaching package: 'dplyr'

The following objects are masked from 'package:lubridate':

    intersect, setdiff, union

The following objects are masked from 'package:stats':

    filter, lag

The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union

# A tibble: 3 x 4
# Groups:   id [2]
     id date          value valuel
  <dbl> <S3: monthly> <dbl>  <dbl>
1     1 1992m1          4.1   NA  
2     2 1992m3          4.5   NA  
3     2 1992m4          3.3    4.5

statar documentation built on Jan. 13, 2021, 9:33 p.m.