library(dplyr,warn.conflicts = FALSE)
# Create dummy data
dtf <- data_frame(t = rep(2001:2003, 2),
c = rep(1:2,each=3),
x = rnorm(6))
# lag over t
dtf %>%
group_by(c) %>% mutate(xt_1 = lag(x))
## # A tibble: 6 x 4
## # Groups: c [2]
## t c x xt_1
## <int> <int> <dbl> <dbl>
## 1 2001 1 0.6976657 NA
## 2 2002 1 0.3243983 0.6976657
## 3 2003 1 -0.4733534 0.3243983
## 4 2001 2 -0.7919892 NA
## 5 2002 2 1.4096323 -0.7919892
## 6 2003 2 0.5602788 1.4096323
# lag over c
dtf %>%
group_by(t) %>% mutate(xc_1 = lag(x))
## # A tibble: 6 x 4
## # Groups: t [3]
## t c x xc_1
## <int> <int> <dbl> <dbl>
## 1 2001 1 0.6976657 NA
## 2 2002 1 0.3243983 NA
## 3 2003 1 -0.4733534 NA
## 4 2001 2 -0.7919892 0.6976657
## 5 2002 2 1.4096323 0.3243983
## 6 2003 2 0.5602788 -0.4733534
computemodel <- function(dtf){
dtf <- dtf %>%
# lag over t
group_by(c) %>% mutate(xt_1 = lag(x)) %>%
# lag over c
group_by(t) %>% mutate(xc_1 = lag(x)) %>%
# place function computation here
mutate(result = xt_1 * xc_1)
return(dtf)
}
computemodel(dtf)
## # A tibble: 6 x 6
## # Groups: t [3]
## t c x xt_1 xc_1 result
## <int> <int> <dbl> <dbl> <dbl> <dbl>
## 1 2001 1 0.6976657 NA NA NA
## 2 2002 1 0.3243983 0.6976657 NA NA
## 3 2003 1 -0.4733534 0.3243983 NA NA
## 4 2001 2 -0.7919892 NA 0.6976657 NA
## 5 2002 2 1.4096323 -0.7919892 0.3243983 -0.2569199
## 6 2003 2 0.5602788 1.4096323 -0.4733534 -0.6672543