Accessing n-dimensional array in R using a function of vector of indexes

1.4k views Asked by At

my program in R creates an n-dimensional array.

PVALUES = array(0, dim=dimensions)

where dimensions = c(x,y,z, ... )

The dimensions will depend on a particular input. So, I want to create a general-purpose code that will:

  1. Store a particular element in the array
  2. Read a particular element from the array

From reading this site I learned how to do #2 - read an element from the array

ll=list(x,y,z, ...)
element_xyz = do.call(`[`, c(list(PVALUES), ll))

Please help me solving #1, that is storing an element to the n-dimensional array.


Let me rephrase my question

Suppose I have a 4-dimensional array. I can store a value and read a value from this array:

PVALUES[1,1,1,1] = 43 #set a value
data = PVALUES[1,1,1,1] #use a value

How can I perform the same operations using a function of a vector of indexes:

indexes = c(1,1,1,1)
set(PVALUES, indexes) = 43
data = get(PVALUES, indexes) ?

Thank you

2

There are 2 answers

0
sda On BEST ANSWER

Thanks for helpful response.

I will use the following solution:

PVALUES = array(0, dim=dimensions) #Create an n-dimensional array
dimensions = c(x,y,z,...,n)

Set a value to PVALUES[x,y,z,...,n]:

y=c(x,y,z,...,n)
PVALUES[t(y)]=26

Reading a value from PVALUES[x,y,z,...,n]:

y=c(x,y,z,...,n)
data=PVALUES[t(y)]
0
IRTFM On

The indexing of arrays can be done with matrices having the same number of columns as there are dimensions:

  # Assignment with "[<-"
  newvals <- matrix( c( x,y,z,vals), ncol=4)     
  PVALUES[ newvals[ ,-4] ]  <- vals

 # Reading values with "["
 PVALUES[ newvals[ ,-4] ]