gpt4 book ai didi

arrays - 数组中的维数和下标数不正确

转载 作者:行者123 更新时间:2023-12-01 01:00:15 25 4
gpt4 key购买 nike

我是使用 R 的新手,因此我的问题可能很简单,但尽管如此,我还是花了很多时间试图弄清楚我做错了什么,但无济于事。在过去的一周里,我在这个网站上发现了很多帮助,搜索其他问题/答案(谢谢!)但作为一个新人,通常很难解释其他人的代码。

我正在尝试构建一个包含多个数据文件的 3 维数组,每个文件的尺寸都相同,为 57x57。

# read in 100 files
Files = lapply(Sys.glob('File*.txt'), read.table, sep='\t', as.is=TRUE)

# convert to dataframes
Files = lapply(Files[1:100], as.data.frame)

# check dimensions of first file (it's the same for all)
dim(Files[[1]])
[1] 57 57

# build empty array
Array = array(dim=c(57,57,100))

# read in the first data frame
Array[,,1] = Files[1]

# read in the second data frame
Array[,,2] = Files[2]
Error in Array[, , 2] = Files[2] : incorrect number of subscripts

# if I check...
Array[,,1] = Files[1]
Error in Array[, , 1] : incorrect number of dimensions

# The same thing happens when I do it in a loop:
x = 0
for(i in 1:100){
Array[,,x+1] = Files[[i]]
x = x + 1
}

Error in Array[, , 1] = Files[[1]] :
incorrect number of subscripts

最佳答案

在进行分配之前,您需要将数据框转换为矩阵:

l <- list(data.frame(x=1:2, y=3:4), data.frame(x=5:6, y=7:8))
arr <- array(dim=c(2, 2, 2))
arr[,,1] <- as.matrix(l[[1]])
arr[,,2] <- as.matrix(l[[2]])
arr
# , , 1
#
# [,1] [,2]
# [1,] 1 3
# [2,] 2 4
#
# , , 2
#
# [,1] [,2]
# [1,] 5 7
# [2,] 6 8

实际上,您可以使用 unlist 在一行中构建数组。应用于要组合的矩阵列表的函数:
arr2 <- array(unlist(lapply(l, as.matrix)), dim=c(dim(l[[1]]), length(l)))
all.equal(arr, arr2)
# [1] TRUE

关于arrays - 数组中的维数和下标数不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24111835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com