Reputation: 2341
I have a panel dataset which is similar to the one below:
Country Ccode Year Happiness Power ID
1 France FR 2000 1000 1000 01
2 France FR 2001 1200 1400 01
3 France FR 2000 1400 1800 02
4 France FR 2001 1600 2200 02
5 UK UK 2000 1000 1000 03
6 UK UK 2001 1000 1000 03
7 UK UK 2000 1000 1000 04
8 UK UK 2001 1000 1000 04
What I am actually interested in is to what degree a variable is elastic with respect to time. In calculating this elasticity I want to make use of the panel data.
This is how far I got:
library(tidyverse)
df <- df %>%
arrange(ID, Year)
group_by(ID) %>%
mutate_if(is.numeric, funs(d = . - lag(.)))
But this just calculates the differences for each variable instead of the variance of a specific one.
Any suggestions on how to do this properly?
Upvotes: 0
Views: 421
Reputation: 6132
If I understand correctly, you want to calculate the variance of the numeric variables per year?
df %>%
arrange(ID, Year) %>%
group_by(Year) %>%
mutate_if(is.numeric, funs(d = var(.)))
Country Ccode Year Happiness Power ID Happiness_d Power_d ID_d
<fct> <fct> <int> <int> <int> <int> <dbl> <dbl> <dbl>
1 France FR 2000 1000 1000 1 40000. 160000. 1.67
2 France FR 2001 1200 1400 1 80000. 320000. 1.67
3 France FR 2000 1400 1800 2 40000. 160000. 1.67
4 France FR 2001 1600 2200 2 80000. 320000. 1.67
5 UK UK 2000 1000 1000 3 40000. 160000. 1.67
6 UK UK 2001 1000 1000 3 80000. 320000. 1.67
7 UK UK 2000 1000 1000 4 40000. 160000. 1.67
8 UK UK 2001 1000 1000 4 80000. 320000. 1.67
Upvotes: 0