我的数据框看起来像这样:
d.v <- data.frame(rnorm(13),type="v")
d.w <- data.frame(rnorm(13),type="w")
d.x <- data.frame(rnorm(13),type="x")
d.y <- data.frame(rnorm(13),type="y")
d.z <- data.frame(rnorm(13),type="z")
all<- rbind(d.v,d.w,d.x,d.y,d.z)
colnames(all) <- c("val","type")
library(reshape2)
allM <- melt(all, id.vars = "type")
allList <- split(allM$value, interaction(allM$type, allM$variable))
我想要做的是创建矩阵的组合 看起来像这样:
[[1]]
v.val v.val
[1,] -0.17392355 -0.17392355
[2,] 0.32196517 0.32196517
[3,] ......
..... # In actuality there are 13 lines for each chunk
[[2]]
v.val w.val
[1,] -0.17392355 0.65036871
[2,] 0.32196517 0.32741115
[3,] ......
..... # In actuality there are 13 lines for each chunk
# etc. in the following combination manner (15 combinations)
# I.e, v-w and w-v are the same, hence we only keep one of them
v-v, v-w,v-x,v-y,v-z,w-w,w-x,w-y,w-z,x-x,x-y,x-z,y-y,y-z,z-z
但是为什么下面的代码失败了:
> unlist(lapply(c(1, 3), function(x) lapply(c(1 ,3), function(y) do.call(cbind,allList[c(x,y)]))), recursive=FALSE)
这样做的正确方法是什么?
答案 0 :(得分:1)
如下所示:
library(gtools) ## To get the function combinations()
theCombs <- combinations(length(allList), 2, names(allList),
repeats.allowed = TRUE)
## Use lapply instead of apply along rows so that list is returned
res <- lapply(seq_len(nrow(theCombs)), function(x) {
## EDIT: This should account for combinations of any number of items
do.call(cbind, allList[theCombs[x, ]])
})
lapply(res, head, 2)
## [[1]]
## v.val v.val
## [1,] 1.593721 1.593721
## [2,] 2.182464 2.182464
##
## [[2]]
## v.val w.val
## [1,] 1.593721 -0.7707361
## [2,] 2.182464 0.2610388
## etc...