Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write and read 3D arrays in R

I have a 3D array in R constructed as (although the names don’t seem to show up):

v.arr <- array(1:18, c(2,3,3), dimnames = c("A", "B", "X",
                          "Y","Z","P","Q","R"))

and it shows up like this when printed to the screen:

, , 1

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

, , 2

     [,1] [,2] [,3]
[1,]    7    9   11
[2,]    8   10   12

, , 3

     [,1] [,2] [,3]
[1,]   13   15   17
[2,]   14   16   18

I write it out to a file using:

write.table(v.arr, file = “Test Data”)

I then read it back in with:

test.data <- read.table(“Test Data”)

and I get this:

  X1 X2 X3 X4 X5 X6 X7 X8 X9
1  1  3  5  7  9 11 13 15 17
2  2  4  6  8 10 12 14 16 18

Obviously, I need to do something to either structure the file before writing or restructure it on the read-back to get back the 3D array. I can always restructure the data that I get from reading. Is that the best approach? Thanks in advance.

like image 690
Ernie Avatar asked May 19 '15 20:05

Ernie


People also ask

How do you make a 3 dimensional array in R?

Create 3D array using the dim() function in R We can create a multidimensional array with dim() function. We can pass this dim as an argument to the array() function. This function is used to create an array. Where data_inputs is the input data that includes list/vectors.

How do you declare a 2-D array in R?

Two-dimensional arraysA matrix is a two dimensional array. A matrix can also be created using the array() function, but now the dim= argument has two numbers: the first being the number of rows in the matrix and the second the number of columns in the matrix.

How do you access an array of elements in R?

An array in R can be created with the use of array() function. List of elements is passed to the array() functions along with the dimensions as required. dimnames : Default value = NULL.


1 Answers

Your issue is that you are using write.table to do this, so it is (I believe) coercing your array to a table. If you are looking to save it and don't mind that it would be in an R-specific format, you can easily use the save and load functions.

save(v.arr,file = "~/Desktop/v.arr.RData")
rm(list=ls())

load("~/Desktop/v.arr.RData")
v.arr
like image 128
TARehman Avatar answered Nov 13 '22 23:11

TARehman