r - 将矩阵划分为 R 中的列表时出现奇怪的输出

标签 r matrix functional-programming

我一直在尝试编写一个接受矩阵 (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:16, nrow = 2)
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
# [1,]    1    3    5    7    9   11   13   15
# [2,]    2    4    6    8   10   12   14   16

cutvec <- c(2,5)

首先,沿着cutvec切割mat的列号:

cuts <- cut(seq(ncol(mat)), c(0, cutvec - 1))

然后您可以使用tapply 创建一个包含子集的列表:

tapply(seq(ncol(mat)), cuts, function(x) mat[, x, drop = FALSE])

# $`(0,1]`
#      [,1]
# [1,]    1
# [2,]    2
#
# $`(1,4]`
#      [,1] [,2] [,3]
# [1,]    3    5    7
# [2,]    4    6    8

关于r - 将矩阵划分为 R 中的列表时出现奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20446098/

相关文章:

r - 如何每天运行两次 R 脚本?

Rcharts nPlot() 离散/多条形图百分比

r - 每组两个日期之间的平均时间差

python - 使用 python 比较/提取矩阵中的数据 (2.6.1)

algorithm - 有效地构造一个方阵,每行都有唯一的数字

C++:行为就像函数本身一样的函数包装器

r - 使用 dplyr 按多个行和列匹配对数据帧进行子集化

r - 如何在R中堆叠多个矩阵

algorithm - 寻找所有可能和独特的组合

java - 在高阶函数中调用带有参数的 lambda