Creating T-1 variable | R

49 Views Asked by At

I would like to create a new variable sales.T.minus.1 which will present the value of sales from year - 1. I created a replicable example below:

  library(plm)
  library(dplyr)

  data <- pdata.frame(Cigar)
    
  data("Cigar")
    
  data <- data %>%
    mutate(sales.T.minus.1 = lag(sales, 1))

Unfortunately this code is not working. The value in variable sales.T.minus.1 is the same as in variable sales.

year sales sales.T.minus.1
64 95.4 95.4

How can I achieve the result I want?

The result I want is:

year sales sales.T.minus.1
64 95.4 93.9
65 98.5 95.4
2

There are 2 best solutions below

0
Quinten On

Try using dplyr::lag because there may be some conflicting functions across package you have installed. And you want to use lag 1 instead of 2. When running it should work like this:

library(plm)
library(dplyr)

data("Cigar")

data <- pdata.frame(Cigar)

data <- data %>%
  mutate(sales.T.minus.1 = dplyr::lag(sales, 1))

Created on 2024-03-06 with reprex v2.0.2

0
Murad Khalilov On

if lag function doesnt work, then you can use shift function from data.table, it is faster than dplyr/lag


library(plm)
library(data.table)

data <- pdata.frame(Cigar)

data("Cigar")

data <- data %>%
  mutate(sales.T.minus.1 = data.table::shift(sales, n = 2, fill = NA))