简体   繁体   中英

R: create an array of matrices from a list

I am trying to create an array from matrices. The matrices are all of identical dimensions (NxN). I have every matrix in a single csv file without header. Data are tab delimited. In other threads it was suggested to do it as follows:

temp = list.files(pattern="*.csv")
named.list <- lapply(temp, read.csv,header=FALSE, sep = "")
arr <- abind(named.list)

However, this does not create what I want. This creates a 2-dimenaional Nx(N*k) data frame (where N = columns/rows and k = number of matrices). So in my case I have 5 matrices, 40 columns and 40 rows each. Using abind creates a [1:40, 1:200] data frame.

> str(arr)
 int [1:40, 1:200] 0 1 0 0 0 0 0 0 0 0 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:200] "V1" "V2" "V3" "V4" ...

What I want is a [1:40, 1:40, 1:5] three-dimensional array of matrices:

> str(z)
 int [1:40, 1:40, 1:5] 0 1 0 0 0 0 0 0 0 0 ...

I think my fundamental problem is that I cannot manage to convert the list of data frames in named.list to a list of matrices.

I solved it, the "abind" got me close. The following line was missing:

arr2<-array(arr,dim= c(40,40,5))

This gives me:

str(arr2)
 int [1:40, 1:40, 1:5] 0 1 0 0 0 0 0 0 0 0 ...

abind is the way to go. If rbindlist was used beforehand, the structure of the individual data sets gets messed up.

this worked for me

temp = list.files(pattern="*.csv")

r <- simplify2array(temp)

However, the resulting array had dimensions [nrow, ncol, n] where the first two elements are matrix dimensions and the last is the number of matrices stored in r. My specific analysis required [n, nrow, ncol] to achieve this change I used the aperm function as follows r <- aperm(r, c(3,1,2)) based on this answer function from base package that is a generalization of the transpose t() function

You can use:

library(data.table)
arr <- rbindlist(named.list ,use.names = T,fill = T);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM