我一直在嘗試編寫一個函數,該函數需要矩陣(x)和向量(cut.vec)並輸出一個列表,其中每個列表元素都是輸入矩陣中某些列的組合。輸入向量中的每個元素都是要分割矩陣的索引。然後我想將每個分區保存到列表中的元素並返回該列表。將矩陣分割成列表中的奇怪輸出R
這裏是我到目前爲止有:
這是我跑實際的功能:
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 = c(6,8,17)'將'cutvec'轉換爲索引列表。 '.ls < - mapply(「:」,c(1,cutvec)[ - length(c(1,cutvec))],cutvec - 1)'然後'lapply(.ls,...)' –
@MatthewLundberg edit.Done。對於那個很抱歉。我希望現在更清楚 – Saren