R中面板数据中的相关矩阵 [英] Correlation matrix in panel data in R
问题描述
我有一个时间序列面板数据集,其结构如下:
df<-data.frame(
year = c(2012L,2013L,2014L,2012L,2013L,2014L ),
id = c(1L,1L,1L,2L,2L,2L),
c = c(11L,13L,13L,16L,15L,15L)
)
#>年ID c
#> 1 2012 1 11
#> 2 2013 1 13
#> 3 2014年1 13
#> 4 2012 2 16
#> 5 2013 2 15
#> 6 2014 2 15
我想在给定ID的情况下找到C列中的值之间的互相关数。
与此类似:
#> 1 2
#> 1 1 0.8
#> 2 0.8 1
我一直在使用dplyr包来查找面板中两个变量之间的互相关数据,但由于某种原因,我无法对按ID分组的一个可验证的互相关函数执行相同的操作。
如果您已经在使用 tidyverse
工具,则应尝试< a href = https://github.com/dgrtwo/widyr rel = nofollow noreferrer> widyr
。
其功能重塑为更宽的范围,获得相关性,并再次给您提供整洁的数据框。
(请注意,我对示例数据进行了少许更改匹配 akaDrHouse的答案。
< pre class = lang-r prettyprint-override>
df<-data.frame(
year = c(2012L,2013L,2014L,2012L,2013L,2014L),
id = c(1L,1L,1L,2L,2L,2L),
c = c(11L,13L,13L,16L,15L,156L)
)
df
#>年ID c
#> 1 2012 1 11
#> 2 2013 1 13
#> 3 2014 1 13
#> ; 4 2012 2 16
#> 5 2013 2 15
#> 6 2014 2 156
widyr :: pairwise_cor(df,id,year,c)
#>#小动作:2 x 3
#> ; item1 item2相关性
#> < int> < int> < dbl>
#> 1 2 1 0.4946525
#> 2 1 2 0.4946525
widyr :: pairwise_cor(df,id,year,c,upper = FALSE)
#> #小动作:1 x 3
#> item1 item2相关性
#> < int> < int> < dbl>
#> 1 1 2 0.4946525
I have a time-series panel dataset which is structured in the following way:
df <- data.frame(
year = c(2012L, 2013L, 2014L, 2012L, 2013L, 2014L),
id = c(1L, 1L, 1L, 2L, 2L, 2L),
c = c(11L, 13L, 13L, 16L, 15L, 15L)
)
#> year id c
#> 1 2012 1 11
#> 2 2013 1 13
#> 3 2014 1 13
#> 4 2012 2 16
#> 5 2013 2 15
#> 6 2014 2 15
I would like to find the cross-correlation between values in column C given their id number. Something similar to this:
#> 1 2
#> 1 1 0.8
#> 2 0.8 1
I have been using dplyr package to find the cross-correlation between two variables in my panel data but for some reason, I can't do the same for cross correlation in one veriable grouped by id.
If you are already using tidyverse
tools, you should try widyr
.
Its functions reshape to wide, get the correlations, and give you back a tidy data frame again.
(Note I changed the sample data slightly to match akaDrHouse's answer.
df <- data.frame(
year = c(2012L, 2013L, 2014L, 2012L, 2013L, 2014L),
id = c(1L, 1L, 1L, 2L, 2L, 2L),
c = c(11L, 13L, 13L, 16L, 15L, 156L)
)
df
#> year id c
#> 1 2012 1 11
#> 2 2013 1 13
#> 3 2014 1 13
#> 4 2012 2 16
#> 5 2013 2 15
#> 6 2014 2 156
widyr::pairwise_cor(df, id, year, c)
#> # A tibble: 2 x 3
#> item1 item2 correlation
#> <int> <int> <dbl>
#> 1 2 1 0.4946525
#> 2 1 2 0.4946525
widyr::pairwise_cor(df, id, year, c, upper = FALSE)
#> # A tibble: 1 x 3
#> item1 item2 correlation
#> <int> <int> <dbl>
#> 1 1 2 0.4946525
这篇关于R中面板数据中的相关矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!