r - 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 没有此类索引
有任何想法吗?
解决方案
这是一种通用的方法,使用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
推荐阅读
- c# - 未设置 Toast 通知组属性
- c++ - 从 const 限定类方法操作属于 std::unique_ptr 的 std::mutex 是否安全?
- streamlit - Warp10 和流线型集成?
- python - 使用 selenium (Python) 从 ui-datepicker-calendar 中选择生日
- ios - SwiftUI - 重音,前景色和色调之间的区别?
- html - 如何让我的表单有 2 个 div 始终居中在页面上
- node.js - heroku node js创建文件夹问题
- node.js - Express 路线在内部和 Postman 测试中工作,但在 Heroku 上出错了 500(大部分)
- java - 在 Java 密钥库中导入 pkcs12 (.p12) 客户端证书文件时,CertificateChain 为空
- excel - 使用数组删除工作表