[R] Convert 2-dim array to 3-dim array

Petr Savicky savicky at cs.cas.cz
Mon Jun 4 17:37:20 CEST 2012


On Mon, Jun 04, 2012 at 11:08:24AM +0200, David Zastrau wrote:
> Hello R-users,
> 
> I'd like to load data from a CSV-file to a 3-dimensional array. However 
> the default seems to be 2-dimensional. It would also be ok to load the 
> data and then convert it to a 3-dimensional structure.
> 
> I've been trying:
> 
>    dat = read.csv(filename)
>    myArr = as.array(dat, dim = c(12,100,3))
> 
> However, I get an error message:
> 
> Error in `dimnames<-.data.frame`(`*tmp*`, value = list(n)) :
> invalid 'dimnames' given for data frame

Hello:

The structure obtained form read.csv() is a data frame, which is a list
of columns of equal length. You can convert it to a matrix using
as.matrix() and then perform further transformation. The command
array(as.matrix(dat), dim = c(12,100,3)) makes sense if either
the matrix is 1200 times 3 or if it is 12 times 300. In the former
case, the row number 1:1200 will be translated to the values of the
first two indices. In the latter case, the column number 1:300 will
be translated to the last two indices.

Hope this helps.

Petr Savicky.



More information about the R-help mailing list