# Generating time-varying covariates with a diminishing correlation structure

#1

I’m generating panel data and I am interested in generating a time-varying covariate that is correlated with previous values of a said covariate. For example, consider the variable x1 below:

``````panels <- fabricate(
countries = add_level(N = 150, country_fe = runif(N, 1, 10)),
years = add_level(N = 25, year_shock = runif(N, 1, 10), nest = FALSE),
obs = cross_levels(
by = join(countries, years),
x1 = rnorm(N,0,1),
new_variable = country_fe + year_shock*Ui + rnorm(N, 0, 2),
Post = ifelse(tr==1 & years == '25', 1, 0)
)
)
``````

Instead of generating x1 at each year independent I want to generate it with a given correlation structure with prior x1 values that diminishes with time. Is it possible to do so in the fabricate call? Or am I better off generating it via mvnorm prior to fabricate and then plugging it in (as a long matrix)?

Thanks.

#2

I would probably move the x1 creation in to a seperate step. modify_level has an option for split-apply-combine processing of data, and since your data is already sorted by time, you can take advantage of that and be a bit looser with the syntax.

Within a group, you can just multiply rnorm by the chol of the variance-covariance matrix desired, unless you need something fancier. Another option would be `arima.sim`.

Here is a rough sketch of what it could look like:

``````panels <- fabricate(
countries = add_level(N = 150, country_fe = runif(N, 1, 10)),
years = add_level(N = 25, year_shock = runif(N, 1, 10), nest = FALSE),
obs = cross_levels(
by = join(countries, years),
new_variable = country_fe + year_shock*Ui + rnorm(N, 0, 2),
Post = ifelse(tr==1 & years == '25', 1, 0)
),
obs = modify_level(
x1 = chol(VCov) %*% rnorm(N,0,1),
by = "countries"
)
)``````