Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Converting a multidimensional array to vector and back to multidimensional array

I have an R array start_arr with dimensions i x j x k representing number of rows, number of columns and the depth respectively. Each dimension is named. I can to convert this array to a (1-dimensional) vector intermediate_vec. I then need to convert this 1D vector back into the original i x j x k array end_arr. I'm just looking for generic functions array2vec and vec2array to do the transformation in a way that preserves how elements are arranged when going from array to vector to array (i.e. that the element at 1,1,1 goes to vector element 1 and back to array element 1,1,1; element at 1,2,1 goes to vector element 2 and back to array element 1,2,1 etc). The particular way the elements are placed in intermediate_vec isn't important, as long as they end up in the exact same positions in end_arr as in start_arr.

I can do this with a C-like iterative syntax but I'm sure there's some declarative way of doing this in R that's faster.

like image 528
elbord77 Avatar asked Jun 15 '26 20:06

elbord77


1 Answers

1) Suppose we have array arr as shown in the first line. Then use c to convert to a vector vec and perform the transformation of adding 100 to each element. Then reshape it back with the same names giving arr2.

arr <- array(1:24, 2:4, dimnames = list(letters[1:2], LETTERS[1:3], month.abb[1:4]))
vec <- c(arr)
arr2 <- replace(arr, TRUE, vec + 100)

# check 
all(arr2 - arr == 100)
## [1] TRUE

2) This would also work:

arr2a <- array(vec + 100, dim(arr), dimnames = dimnames(arr))

identical(arr2, arr2a)
## [1] TRUE
like image 198
G. Grothendieck Avatar answered Jun 17 '26 11:06

G. Grothendieck