I have a panel dataset at the firm-year level. I would first like to calculate, within each firm, the correlation of variable x across years. I would then like to calculate the average of that correlation across all firms. I am unsure how best to accomplish this. I have considered calculating a correlation matrix for each firm, then taking the average of each matrix. Something like the below code (taken from
this discussion):
Code:
levelsof firm, local(levls)
foreach i of local levels {
corr demand2012 demand2013 demand2014 demand2015 demand2016 demand2017 demand2018 if firm == `i'
mata {
C = st_matrix("r(C)")
mean(abs(select(vech(C), vech(C) :< 1)))
}
Running this displays the average of the correlation matrix below the diagnol for each firm in the results window. However, I am unfamiliar with mata and thus am not sure how to store the results as variable values.
I am wondering a) if it would be possible to add to the above code to store the results as variable values or b) if there is a more efficient/accurate way of calculating the within-firm correlation of variable x across years.
I have gone through documentation and the usual search routes and haven't yet found a solution. I am using Stata 15.
0 Response to Calculate average within-unit correlation of variable across time
Post a Comment