【发布时间】:2013-12-25 02:45:08
【问题描述】:
我一直在尝试编写一个函数,它接收矩阵 (x) 和一个向量 (cut.vec) 并输出一个列表,其中列表的每个元素都是输入矩阵中某些列的组合.输入向量中的每个元素都是要对矩阵进行分区的索引。然后我想将每个分区保存到列表中的一个元素并返回该列表。
这是我目前所得到的:
这是我正在运行的实际函数:
make.cut <- function(x, cut.vec){
ran.once <- 0 #This checks for first run
out <- list() #This creates the output list
temp.matrix <- matrix() #For holding data
for(i in 1:length(cut.vec)){
for(n in 1:cut.vec[i]){
if(cut.vec[i]<n){
#Do nothing
}else{
hold <- x[,n]
if(ran.once != 0){
temp.matrix <- cbind(temp.matrix, hold)
}else{
temp.matrix <- hold
ran.once <- 1
}
}
}
out[[i]] <- temp.matrix
temp.matrix <- matrix()
}
return(out)
}
当我运行它时,我会得到一个列表,但只有第一个元素是正确的。除第一个元素外,每个元素仅包含输入矩阵的一列。
**Example Input**
x<-matrix(c(341, 435, 834, 412, 245, 532.2, 683.4, 204.2, 562.7, 721.5, 149, 356, 112, 253, 211, 53, 92, 61, 84, 69), nrow=4)
x= 341 435 834 412 245
532.2 683.4 204.2 562.7 721.5
149 356 112 253 211
53 92 61 84 69
cut.vec = c(2, 3, 5)
out <- make.cut(x, cut.vec):
a <- out[[1]]
b <- out[[2]]
c <- out[[3]]
**Intended Output**
a= 341 435
532.2 683.4
149 356
53 92
b= 834
204.2
112
61
c= 412 245
562.7 721.5
253 211
84 69
**Actual Output**
a= 341 435
532.2 683.4
149 356
53 92
b= 435
683.4
356
92
c= 834
204.2
112
61
我可以从控制台手动执行此操作,一次一个元素并且它可以工作,但每次我尝试使用 make.cut 函数执行此操作时它都会中断。
这是我在终端中手动完成的:
cut.vec<-c(3, 5)
a<-x[,1]
b<-x[,2]
c<-x[,3]
temp <- cbind(a,b,c)
out[[1]] <- temp
cut.vec[2] 等于 5
a<-x[,4]
b<-x[,5]
temp <- cbind(a,b)
out[[2]] <- temp
但是,当我尝试在函数中应用相同的方法时,它会中断。
【问题讨论】:
-
既然你知道索引,也许你可以这样做:
mat = matrix(1:24, nrow = 4);lapply(list(1:3, 4:5), function(x) as.matrix(mat[,x]))? -
您可以将
cutvec转换为索引列表,例如:cutvec = c(6, 8, 17);.ls <- mapply(":", c(1, cutvec)[-length(c(1, cutvec))], cutvec - 1),然后是lapply(.ls, ...) -
@MatthewLundberg 编辑。完成。对于那个很抱歉。我希望现在更清楚了
-
@alexis_laz 我试过了,但问题是当函数运行时,除了第一次运行之外,它在错误的点上剪切。我用示例输入和输出更新了问题,以使事情更清楚。谢谢
-
试试这个,也许:
.ls <- mapply(":", c(1, cut.vec+1)[-length(c(1, cut.vec+1))], cut.vec);lapply(.ls, function(z) as.matrix(x[,z]))。另外,在x = matrix(...)中使用byrow = T来构建您显示的x。
标签: r matrix functional-programming