R extracting array from list [duplicate] - arrays

This question already has an answer here:
Select multiple elements from a list
(1 answer)
Closed 4 years ago.
I need help with extracting array from list.
array1 <- array(c(1,2,3), dim = c(3,3,3))
array2 <- array(c(10,20,30), dim = c(3,3,3))
A <- list(array1,array2)
B <- A[1]
"A" is list of two arrays. When I want to extract for example first array and assign it to "B", B isn't array, but it is also list. How can I access data stored in B? B[1,1,1] doesn't work.

Use [[ to extract element in a list. If you use [, the output would still be a list.
array1 <- array(c(1,2,3), dim = c(3,3,3))
array2 <- array(c(10,20,30), dim = c(3,3,3))
A <- list(array1,array2)
B <- A[[1]]

If we are using magrittr, then extract2 can be used for the same purpose
library(magrittr)
B <- A %>%
extract2(1)

Related

R Accessing vector inside list inside Array

I have a very long Array (1955x2417x1) in R where each position stores a list of two vector (named "max" and "min") of length 5.
I would like to find a simple way to create a multidimensional array (dim 1955x2417x5) where each position holds a single value from vector "max"
I have looked at answers such as array of lists in r
but so far without success.
I know I can access the list in each position of the array using
myarray[posX, PosY][[1]][["max"]]
but how to apply that to the whole Array?
SO far I have tried
newArray <- array( unlist(myarray[][[1]][["max"]]), c(1955, 2417, 5))
and
NewArray <-parApply(cl, myarray, c(1:2), function(x) {
a=x[[1]][["max"]]
} )
but the results are not right.
Do you have any suggestion?
Let
e <- list(min = 1:3, max = 4:6)
arr <- array(list(e)[rep(1, 8)], c(2, 4))
dim(arr)
# [1] 2 4
Then one option is
res <- apply(arr, 1:2, function(x) x[[1]][["max"]])
dim(res)
# [1] 3 2 4
and, if the order of dimensions matters,
dim(aperm(res, c(2, 3, 1)))
# [1] 3 2 4

How to bind arrays by columns in R...?

Looking for the smartest and shortest way to bind the following two arrays in R. Excepted output is also given...
#Creating two arrays
(a <- array(c(1:9,19:27), dim = c(3,3,2)))
(b <- array(c(10:18,28:36), dim = c(3,3,2)))
#Wanted array by binding a and b
(wanted <- array(1:36, dim = c(3,6,2)))
Thanks a lot...
We can use abind
library(abind)
res <- abind(a, b, along = 2)
attr(res, "dimnames") <- NULL
identical(res, wanted)
#[1] TRUE

Multilayered-LIST-to-ARRAY-transformation in R and any better way than using loops

Looking for the smartest and shortest code to solve the following issue in R. Two non-proper solutions are provided...
#Generating a multi-layered list
m <- matrix(1:50, ncol = 5, byrow = TRUE)
mList <- list(m[1:5,], m[6:10,])
mList
#Transforming list to array: Option one
mArrayOne <- array(c(mList[[1]], mList[[2]]), dim = c(5,5,2))
mArrayOne
#Transforming list to array: Option two
mArrayTwo <- array(numeric(), dim = c(dim(mList[[1]]), length(mList)))
for(i in 1:length(mList)){mArrayTwo[,,i] <- mList[[i]]}
mArrayTwo
Any hint is welcome - thanks...
We can just unlist the list and create the array
array(unlist(mList), dim = c(5,5,2))

Transform two arrays in to one data frame in R

I have two arrays coming from a postgreSQL database as following.
iarray
{9.467182035,9.252423958,9.179368178,9.142931845,9.118895803,9.098669713,9.093398102,9.092035392,9.091328028,9.090594437,9.090000456,9.089253543......keeps going on}
varray
{-1.025945126,-0.791203874,-0.506481774,-0.255416444,-0.028424464,0.188855034,0.390787963,0.579327969,0.761521769 ...keeps going on}
Both arrays have equal number of entries. I want to convert these to a data frame hence I can draw a graph of i over v.
How should I proceed?
I tried n<-gsub("^\\{+(.+)\\}+$", '\\1', iarray) to remove the {} and
n2 <- strsplit(n, ",") to remove the commas.
Assuming you are getting iarray & varray as strings :
iarray = "{9.467182035,9.252423958,9.179368178,9.142931845}"
varray = "{-1.025945126,-0.791203874,-0.506481774,-0.255416444}"
n<-gsub("^\\{+(.+)\\}+$", '\\1', iarray)
n1 <- strsplit(n,",")
n1 <- unlist(n1)
df <- as.data.frame(n1)
n<-gsub("^\\{+(.+)\\}+$", '\\1', varray)
n2 <- strsplit(n,",")
n2 <- unlist(n2)
df <- cbind(df,n2)
This seems one of the few occasions to correctly use eval(parse()):
df<-list(iarray,varray)
df<-data.frame(lapply(df,
function(x) eval(parse(text=sub("\\}$",")",sub("^\\{","c(",x))))
))
names(df)<-c("iarray","varray")
We just replace the { with (, add a c at the beginning and iarray and varray become command lines to create vectors which we parse and eval.

How to create sub-arrays access the i-th dimension of an array within for()?

In a for-loop, I run in i over an array which I would like to sub-index in dimension i. How can this be done? So a minimal example would be
(A <- array(1:24, dim = 2:4))
A[2,,] # i=1
A[,1,] # i=2
A[,,3] # i=3
where I index 'by foot'. I tried something along the lines of this but wasn't successful. Of course one could could create "2,," as a string and then eval & parse the code, but that's ugly. Also, inside the for loop (over i), I could use aperm() to permute the array such that the new first dimension is the former ith, so that I can simply access the first component. But that's kind of ugly too and requires to permute the array back. Any ideas how to do it more R-like/elegantly?
The actual problem is for a multi-dimensional table() object, but I think the idea will remain the same.
Update
I accepted Rick's answer. I just present it with a for loop and simplified it further:
subindex <- c(2,1,3) # in the ith dimension, we would like to subindex by subindex[i]
for(i in seq_along(dim(A))) {
args <- list(1:2, 1:3, 1:4)
args[i] <- subindex[i]
print(do.call("[", c(list(A), args)))
}
#Build a multidimensional array
A <- array(1:24, dim = 2:4)
# Select a sub-array
indexNumber = 2
indexSelection = 1
# Build a parameter list indexing all the elements of A
parameters <- list(A, 1:2, 1:3, 1:4)
# Modify the appropriate list element to a single value
parameters[1 + indexNumber] <- indexSelection
# select the desired subarray
do.call("[", parameters)
# Now for something completely different!
#Build a multidimensional array
A <- array(1:24, dim = 2:4)
# Select a sub-array
indexNumber = 2
indexSelection = 1
reduced <- A[slice.index(A, indexNumber) == indexSelection]
dim(reduced) <- dim(A)[-indexNumber]
# Also works on the left-side
A[slice.index(A, 2)==2] <- -1:-8

Resources