嵌套应用功能

时间:2015-12-23 14:13:01

标签: r nested regression apply

我有两个矩阵,想要应用线性回归。简而言之,我希望得到a的每个列与b因子之间的回归的p值,具有代表性。

所以我想计算(数字显示列)之间的关联:

a1 ~ b1
a1 ~ b2
...
a2 ~ b1
a2 ~ b2
...
a3 ~ b1
...

两个数据集:

set.seed(1232)
a <- matrix(runif(100,min=6,max=14),10)
b <- matrix(sample(c(0,1),100,replace = T),10)

我尝试使用循环,这可行,但速度太慢了:

res <- NULL
for( i in 1:ncol(a)){
  tmp <- apply(b,2,function(y,x) summary(lm(x~y))$coefficients[2,4],a[,i])
  res <- cbind(res,tmp)
  print(i)
}

所以我尝试使用这样的嵌套应用函数,但它不起作用。你有什么想法吗?

apply(b, 2, function(y,x) apply(x,2,function(x,y) summary(lm(x~y))$coefficients[2,4]), a)

2 个答案:

答案 0 :(得分:2)

你不需要回归:

res <- outer(seq_len(ncol(a)),
      seq_len(ncol(b)),
      FUN = Vectorize(function(k, l) cor.test(a[, k], b[, l])$p.value))

res[4, 3]
#[1] 0.3753466
summary(lm(a[,4] ~ b[, 3]))$coefficients[2,4]
#[1] 0.3753466

您当然可以以同样的方式使用lm代替cor.test

或者,您可以使用package psych:

library(psych)
corr.test(as.data.frame(a), as.data.frame(b), adjust = "none")$p

当然,调整多次测试的默认值提醒我们你真的应该这样做。

答案 1 :(得分:1)

试试这个:

apply(b, 2, function(x) apply(a, 2, function(y) summary(lm(x~y))$coefficients[2,4]))
           [,1]      [,2]      [,3]        [,4]      [,5]       [,6]        [,7]       [,8]
 [1,] 0.8625602 0.2411563 0.7612476 0.509436082 0.3577235 0.45874974 0.360808572 0.05617883
 [2,] 0.4136582 0.1186081 0.5161454 0.819513642 0.7813467 0.75912163 0.908950370 0.80584144
 [3,] 0.5388209 0.8055687 0.7549796 0.935750996 0.0646300 0.79523596 0.973429634 0.55095667
 [4,] 0.9930913 0.9622925 0.3753466 0.552830253 0.9636374 0.75312925 0.997724288 0.39246169
 [5,] 0.2238149 0.4628420 0.5969530 0.007438859 0.4620672 0.42912431 0.007249279 0.50000827
 [6,] 0.8022590 0.2352531 0.8990588 0.760952083 0.5794459 0.06170874 0.459247551 0.94625005
 [7,] 0.4928149 0.1462937 0.5620584 0.554991195 0.6128055 0.55182670 0.874316882 0.55169689
 [8,] 0.6631461 0.6260493 0.7679088 0.714076186 0.1254954 0.14316276 0.961166356 0.55342849
 [9,] 0.9449110 0.2703502 0.5328246 0.533630873 0.2036671 0.87532137 0.402796595 0.24040106
[10,] 0.4151634 0.3584605 0.6923008 0.599701142 0.4649529 0.98238156 0.628130071 0.17310254
            [,9]      [,10]
 [1,] 0.38552290 0.03078476
 [2,] 0.03466566 0.64135540
 [3,] 0.44603945 0.57578621
 [4,] 0.47220820 0.45735156
 [5,] 0.33202974 0.63330763
 [6,] 0.09964719 0.19571414
 [7,] 0.72649867 0.61591287
 [8,] 0.22911914 0.84239810
 [9,] 0.30766378 0.12782897
[10,] 0.01139275 0.46489123