Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R: how to abind many arrays, using names stored in a character vector

I have a character vector of names of arrays in my environment. e.g.

test.list <- (paste0("test.array",1:3))

I want to use these names to abind the arrays, something like:

test.array.bind1 <- abind(test.list[1:3], along = 5)

but that gives the error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error in abind(test.list[1:3], along = 5) : along must be between 0 and 2

I believe it is not treating the input as the names of objects, because it works when I write the names out manually.

test.array.bind <- abind(test.array1, test.array2, test.array3, along = 5)

I tried some variations like:

test.array.bind1 <- abind(paste(test.list[1:3], sep = ","), along = 5)

but get the same error.

The closest questions I have found so far are about data.frames, and suggested solutions don’t directly answer this question, but say how they should be doing their workflow differently such as loading them all in lists they can then run the functions over that they wish to. I don’t think that applies here.

I could have just typed the names out several times over in the hour it has taken me to try to find the solution so far (there are many more than 3 in my real data!), but I keep coming across similar problems so I wondered if there is an automated solution.

>Solution :

We need mget to get the value of the objects in a list, then use abind within do.call

library(abind)
out1 <- do.call(abind, c(mget(test.list[1:3]), along = 5))

NOTE: The [1:3] is not needed if the length of the ‘test.list’ vector is just 3

-testing with OP’s code

> out2 <- abind(test.array1, test.array2, test.array3, along = 5)
> all.equal(out1, out2, check.attributes = FALSE)
[1] TRUE

data

test.array1 <- array(1:50, dims = c(2, 2, 2, 3, 2))
test.array2 <- array(51:100, dim = c(2, 2, 2, 3, 2))
test.array3 <- array(101:150, dim = c(2, 2, 2, 3, 2))
test.list <- paste0("test.array", 1:3)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading