Incorrect number of dimensions and wrong number of indices in the array

I am new to using R, and so my question may be simple, but nonetheless I spent a lot of time figuring out what I am doing wrong, but to no avail. I found a lot of help on this site last week looking for other questions / answers (thanks!), But as someone new, it is often difficult to interpret other people's code.

I am trying to build a three-dimensional array of several data files, each of which has the same dimensions of 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 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
+4
source share
1 answer

You need to convert your data frames to matrices before completing the task:

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
+4

Source: https://habr.com/ru/post/1543798/


All Articles