简体   繁体   English

R中面板数据中的相关矩阵

[英]Correlation matrix in panel data in R

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. 我想找到给定ID号的C列中的值之间的相互关系。 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. 我一直在使用dplyr包来查找面板数据中两个变量之间的互相关性,但是由于某些原因,对于一个按id分组的可验证的互相关性,我无法做到相同。

Do you mean something like the following? 您是说以下意思吗? I used the reshape package to cast based on the value of your id, followed by the cor() function in baseR. 我使用了reshape包根据您的id的值进行了转换,随后是baseR中的cor()函数。

> mydf <- data.frame(year=c("12","13","14","12","13","14"),id=c(1,1,1,2,2,2),c=c(11,13,13,16,15,156))
> library(reshape2)
> mydf
  year id   c
1   12  1  11
2   13  1  13
3   14  1  13
4   12  2  16
5   13  2  15
6   14  2 156
> my_wide_data <- dcast(mydf, year~id,value.var="c")
> cor(my_wide_data[,2:3])
          1         2
1 1.0000000 0.4946525
2 0.4946525 1.0000000

So @Henrik's comment was much more simple and elegant, so including here. 因此,@ Henrik的评论更加简单和优雅,因此请在此处添加。

> cor(unstack(mydf[ , -1], c ~ id))
          X1        X2
X1 1.0000000 0.4946525
X2 0.4946525 1.0000000

If you are already using tidyverse tools, you should try widyr . 如果您已经在使用tidyverse工具,则应该尝试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. (请注意,我稍微更改了示例数据以匹配akaDrHouse的答案。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM