Fabian Stolz
Fabian Stolz

Reputation: 2095

Setting up a 3D matrix in R and accessing certain elements

I am trying to set up a 3D matrix in R. I guess this is an easy one. However, I didn't find a solution so far. Let's say we want to create a 365x6x4 matrix. Also crucial form me is how I can change one entry in the matrix. Let's say we want to assign the value 204 to the element [304,5,2].

Upvotes: 44

Views: 92220

Answers (3)

Havelock
Havelock

Reputation: 6966

Try this:

ar <- array(someData, c(365, 6, 4));  
ar[304,5,2] <- 204;

where someData might be

someData <- rep(0, 365*6*4);  

or even better maybe

someData <- rep(NaN, 365*6*4);  

Upvotes: 52

Andrie
Andrie

Reputation: 179468

A matrix is a special 2-dimensional case of an array. (Quoting from the help for ?matrix).

So, you need array:

x <- array(rep(1, 365*5*4), dim=c(365, 5, 4))
str(x)
num [1:365, 1:5, 1:4] 1 1 1 1 1 1 1 1 1 1 ...

Set a specific value:

x[305, 5, 2] <- 204

Print one slice:

x[305, , ]
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    1    1    1    1
[3,]    1    1    1    1
[4,]    1    1    1    1
[5,]    1  204    1    1

Upvotes: 20

Tim P
Tim P

Reputation: 1383

Try this simple example (have made the example a fairly small one so it's clear what's going on - I explain below how to tweak it for your precise question!)...

m = array(1:60, dim=c(3,4,5))

m[2,1,5]
[1] 50

m[2,1,5] = -50

m[2,1,5]
[1] -50

Type m to see the whole 3d array :)

In your example, you'd set up your initial array as m = array(NA, dim=c(365,6,4)) (this will fill it with NAs to start with - do you have data to fill it up with?) And the assignment is m[304,5,2] = 204, of course :)

Upvotes: 7

Related Questions