0

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
5
  • 2
    Could you please explain what is not working? Do you get an error? Commented Mar 6, 2024 at 12:26
  • 2
    We can't really tell what result you get or what result you want from what you've presented. Please provide a reproducible example and the desired result. Commented Mar 6, 2024 at 12:26
  • Also, perhaps this answer will get you going in the right direction. Commented Mar 6, 2024 at 12:27
  • Try grouping by state. mutate(sales.T.minus.1 = lag(sales, 2), .by = state). Also, first load the data, then coerce to class 'pdata.frame'. (wrong instructions order in your code.) Commented Mar 6, 2024 at 12:35
  • @Quinten I edited my post, I think it is more reproducible :) Commented Mar 6, 2024 at 12:48

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.