這是我的方法;
# example datas
set.seed(1); y <- matrix(runif(20), ncol=1)
set.seed(2); x1 <- matrix(runif(60), ncol=3)
set.seed(3); x2 <- matrix(runif(80), ncol=4)
set.seed(4); x3 <- matrix(runif(40), ncol=2)
set.seed(5); x4 <- matrix(runif(60), ncol=3)
我由具有COL-數
col.v <- sapply(list(x1,x2,x3,x4), ncol) # ncols of each data
col.comb <- expand.grid(sapply(col.v, seq.int)) # its all combinations
# > head(col.comb, n=4)
# Var1 Var2 Var3 Var4
# 1 1 1 1 1
# 2 2 1 1 1
# 3 3 1 1 1
# 4 1 2 1 1
# 5 2 2 1 1
我t.value通過
申請(col.comb,1,...)
tval <- apply(col.comb, 1, function(a) {
temp <- lm(y ~ x1[,a[1]] + x2[,a[2]] + x3[,a[3]] + x4[,a[4]])
summary(temp)$coefficients[2:5, 3] })
# > head(tval, n=2) # tval is matrix
# x1[, a[1]] x2[, a[2]] x3[, a[3]] x4[, a[4]]
# [1,] -0.05692452 -0.9047370 -0.3758997 1.968530
# [2,] 0.03476527 -0.9260632 -0.3740936 1.965884
我所有組合的矩陣將tval-matrix的每一列改爲
array and combined each
array納入
列表。
results <- list() # results[[1]] is x1's array
for(i in seq.int(length(col.v))) results[[i]] <- array(tval[,i], dim=col.v)
# names(results) <- c("x1", "x2", "x3", "x4") # if you want
results2 <- array(t(tval), dim=c(length(col.v), col.v)) # all.array.version
## results[[1]] is the same as results2[1,,,,] # both is x1's array
# dimnames(results2)[[1]] <- list("x1", "x2", "x3", "x4") # if you need
檢查
c(results[[1]][2,3,2,3], results[[2]][2,3,2,3], results[[3]][2,3,2,3], results[[4]][2,3,2,3])
# [1] 0.54580342 -0.56418433 -0.02780492 -0.50140806
c(results2[1,2,3,2,3], results2[2,2,3,2,3], results2[3,2,3,2,3], results2[4,2,3,2,3])
# [1] 0.54580342 -0.56418433 -0.02780492 -0.50140806
summary(lm(y ~ x1[,2] + x2[,3] + x3[,2] + x4[,3]))$coefficients[2:5,3]
# x1[, 2] x2[, 3] x3[, 2] x4[, 3]
# 0.54580342 -0.56418433 -0.02780492 -0.50140806 # no problem
功能版本(N = 4);
testvars2 <- function(y, x1, x2, x3, x4){
col.v <- sapply(list(x1,x2,x3,x4), ncol)
col.comb <- expand.grid(sapply(col.v, seq.int))
tval <- t(apply(col.comb, 1, function(a) {
temp <- lm(y ~ x1[,a[1]] + x2[,a[2]] + x3[,a[3]] + x4[,a[4]])
summary(temp)$coefficients[2:5, 3] }))
results <- list()
for(i in seq.int(length(col.v))) results[[i]] <- array(tval[,i], dim=col.v)
#results2 <- array(t(tval), dim=c(length(col.v), col.v))
return(results)
}
我的X矩陣有600多列,導致expand.grid出錯。你有什麼建議如何解決它? –
@SevaGumeniuk;如果你想把結果作爲'array',它的'dim'變成'c(ncol(X1),ncol(X2),...,ncol(Xn))'。請嘗試'test_array < - array(1,dim = c(ncol(X1),ncol(X2),...,ncol(Xn)))''。如果R返回與錯誤相關的大小,則不可能將結果'數組'。 – cuttlefish44