首页 > 解决方案 > 如何将 3 个相关矩阵读取为数组

问题描述

我想在一个数组中读取 3 个独立的相关矩阵。我已按照此处所示的方法进行操作,但是出现错误,但不知道为什么。如果有人能看到我的代码并帮助我,我将不胜感激。这是我的代码和模拟数据。

dataDir <- getwd()
## Each matrix is in a csv file
set.seed(22)
## m1
li.A <- matrix(rnorm(100), nrow = 20)
rownames(li.A) <- LETTERS[1:20]
colnames(li.A) <- paste0("S_", ncol = 1:5)
m1 <- cor(t(li.A))
write.csv(m1, file = “m1.csv")

# m2
set.seed(42)
pa.A <- matrix(rnorm(100), nrow = 20)
rownames(pa.A) <- LETTERS[1:20]
colnames(pa.A) <- paste0("S_", ncol = 1:5)
m2 <- cor(t(pa.A))
write.csv(m2, file = “m2.csv")

# m3
set.seed(44)
li.B <- matrix(rnorm(100), nrow = 20)
rownames(li.B) <- LETTERS[1:20]
colnames(li.B) <- paste0("S_", ncol = 1:5)
m3 <- cor(t(li.B))
write.csv(m3, file = “m3.csv")

fileList <- dir(path=dataDir,pattern = ".csv")

## Read all matrices into an array
A <- array(as.numeric(NA),dim=c(20,20,3)) # There are 3 matrices of size 20 x 20
for (i in 1:length(fileList)){
  A[,,i] <- as.matrix(read.delim(file.path(dataDir,fileList[i]), sep = ';', header=TRUE, row.names=1))
}

here is the error.
Error in A[, , i] <- as.matrix(read.delim(file.path(dataDir, fileList[i]),  : 
  replacement has length zero

谢谢!

标签: rarrays

解决方案


该问题将与它sep = ';'相反sep=",",它返回单个字符串列而不是多个列。因此,当我们使用索引进行分配时,它显示了错误

A <- array(as.numeric(NA),dim=c(20,20,3)) # There are 3 matrices of size 20 x 20
 for (i in 1:length(fileList)){
   A[,,i] <- as.matrix(read.delim(file.path(dataDir,fileList[i]), 
       sep = ',', header=TRUE, row.names=1))
 }

dim(A)
#[1] 20 20  3

推荐阅读