如何生成R中的向量组合
我有一个看起来像这样的数据帧:如何生成R中的向量组合,r,dataframe,R,Dataframe,我有一个看起来像这样的数据帧: 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.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)
正确的方法是什么?下面的方法怎么样:
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...
library(gtools)##获取函数组合()
combs下面的例子怎么样:
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...
library(gtools)##获取函数组合()
我不认为你的问题清楚你想要什么样的输出。如果您的输入dfs有13行,您如何从中获得2x2矩阵?@Thomas:它被截断了..以节省空间。为了清晰起见,我已经更新了OP。我认为从你的问题中不清楚你想要什么输出。如果您的输入dfs有13行,您如何从中获得2x2矩阵?@Thomas:它被截断了..以节省空间。为了清晰起见,我更新了OP。@neversaint,编辑过的代码更一般化,去掉了不必要的东西。@neversaint,编辑过的代码更一般化,去掉了不必要的东西。