1

我有如下所示的数据框:

 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)

正确的方法是什么?

4

1 回答 1

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...
于 2013-06-10T07:49:00.537 回答