簡體   English   中英

“在級別 1 上沒有這樣的索引”在 for 循環中添加列時出錯

[英]'No such index at level 1' error on for loop to add columns

我有一個矩陣列表。 每個矩陣有 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 級沒有這樣的索引

有任何想法嗎?

這是使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM