列之间的成对Lepage统计量

时间:2016-04-06 22:15:26

标签: r dplyr

我想知道如何计算数据列之间的成对Lepage统计量,如:

> cbind(v1=rnorm(10), v2=rnorm(10), v3=rnorm(10), v4=rnorm(10))
               v1          v2          v3          v4
 [1,] -2.47148729  0.61727115  1.28285770  0.72974010
 [2,]  0.42657513  0.77615280  1.88207246  0.41295301
 [3,] -0.32480814 -1.75461602 -0.16589154 -0.52731722
 [4,]  0.02760296 -2.08827618 -0.47176830 -0.17416765
 [5,] -0.52760532 -0.20514629  0.15589594 -0.54623986
 [6,] -0.47143259 -0.56666084 -1.35046101 -0.92754741
 [7,]  0.61071291 -1.65132215  1.61024187  0.83128254
 [8,] -0.17746888 -1.09887111 -0.32012303  0.69382341
 [9,] -0.38707069 -0.69628506  0.04597653  0.13479181
[10,]  0.52030680  1.11764587 -1.10243994 -0.83949756

我想要有类似的东西:

     v1.v1 v1.v2 v1.v3 v1.v4   ... v4.v4
[1,]     0     1     2     5   ...     0

cor(x)x是矩阵时的作用相同。我想dplyr可能是一个答案?或者有一个多重采样版本pLepage()

1 个答案:

答案 0 :(得分:0)

考虑使用基础R的服务。不熟悉R中的LePage测试,但使用相关性和您的示例数据:

rdmatrix <- cbind(v1=rnorm(10), v2=rnorm(10), v3=rnorm(10), v4=rnorm(10))
corrmatrix <- sapply(1:ncol(rdmatrix), 
                     function(x,y) cor(rdmatrix[,x], rdmatrix[,y]), 1:ncol(rdmatrix))

#            [,1]       [,2]       [,3]       [,4]
# [1,]  1.0000000 -0.4613219 -0.5661391 -0.1703655
# [2,] -0.4613219  1.0000000  0.1965278  0.2111900
# [3,] -0.5661391  0.1965278  1.0000000 -0.3305471
# [4,] -0.1703655  0.2111900 -0.3305471  1.0000000

要将其展平为一行矩阵,请使用outer()对所有列名称组合和do.call(cbind, ...)进行展平:

# MATRIX OF ALL COLS PAIRINGS
cols <- outer(colnames(rdmatrix), colnames(rdmatrix),               
                      function(y,x) paste0(x, '.', y))   # NOTICE INVERSION OF X AND Y  
# FLATTEN COL NAMES
cols <- do.call(cbind, as.list(cols))                   

# FLATTEN CORR MATRIX DATA
finalmatrix <- do.call(cbind, as.list(corrmatrix))   
# NAME MATRIX COLUMNS
colnames(finalmatrix) <- cols[1,]                

#           v1.v1      v1.v2      v1.v3      v1.v4      
# [1,]          1 -0.4613219 -0.5661391 -0.1703655 
#           v2.v1      v2.v2      v2.v3      v2.v4
# [1,] -0.4613219          1  0.1965278    0.21119
#           v3.v1      v3.v2      v3.v3      v3.v4
# [1,] -0.5661391  0.1965278          1 -0.3305471
#           v4.v1      v4.v2      v4.v3      v4.v4
# [1,] -0.1703655    0.21119 -0.3305471          1