Writing and reading 3D arrays in R

I have a 3D array in R built as (although the names do not seem to be displayed):

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

and this is displayed when printing on 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 am writing it to a file using:

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

Then I read it with:

 test.data <- read.table("Test Data") 

and I get the following:

  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 structure the file before writing or restructuring it on the way back to return a 3D array. I can always restructure the data that I get from reading. Is this a better approach? Thanks in advance.

+6
source share
1 answer

Your problem is that you are using write.table for this, so this is (I believe) forcing your array to a table. If you want to save it and do not mind that it is in R 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 
+5
source

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


All Articles