首页 > 解决方案 > for 循环添加列时出现“级别 1 无此类索引”错误

问题描述

我有一个矩阵列表。每个矩阵有 11 或 12 列,所以我试图将所有矩阵标准化为 12 列。

# Normalize all pages to have 12 columns; some currently have 11 others 12
# 'out' is a list with each element being a matrix
for (i in out) {

  # check if each matrix has less than 12 columns
  if(ncol(out[[i]])<12) {

    # if it does, then insert a column of blanks between columns 1 and 2
    out1 = out[[i]]
    out2 <- cbind(out1[,1],"",out1[,2:11])
    out[[i]] <- out2
  }
}

当我运行代码时,我收到以下消息:

out[[i]] 中的错误:级别 1 没有此类索引

有任何想法吗?

标签: r

解决方案


这是一种通用的方法,使用lapply-

# first a reproducible example
matlist <- list(
  a = matrix(1:6, ncol = 3),
  b = matrix(1:4, ncol = 2)
)

matlist
$a
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

$b
     [,1] [,2]
[1,]    1    3
[2,]    2    4

现在,与问题类似,所有矩阵都应该有 3 列,在第 1 列和第 2 列之间插入缺失的列 -

# get max column number from list
maxcol <- max(sapply(matlist, ncol)) # directly use 12 here if preferred

# update original list
matlist[] <- lapply(matlist, function(x) {
  coldiff <- maxcol - ncol(x)
  if(coldiff > 0) {
    cbind(x[, 1], matrix(NA, nrow(x), coldiff), x[, 2:ncol(x)])
  } else {
    x
  }
})

matlist    
$a
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

$b
     [,1] [,2] [,3]
[1,]    1   NA    3
[2,]    2   NA    4

推荐阅读