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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With