Atia Amin
Atia Amin

Reputation: 429

slicing in R m[:,2,:]

I have an array

> dim(m)
[1]   20   15 2000
> typeof(m)
[1] "double"

I want to slice a (20, 2000) length array that resides in m[:,2,:]. What is the proper way to do it in R?

Upvotes: 0

Views: 44

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368399

In R you use a 'space' to denote all elements along that dimension.

Example from your dimensions:

R> m <- array(0, dim= c(20, 15, 2000))    # boring content
R> str(m)                                 # 'proof' it is 3d
 num [1:20, 1:15, 1:2000] 0 0 0 0 0 0 0 0 0 0 ...
R> str( m[, 2, ] )                        # 'proof' it is 2d
 num [1:20, 1:2000] 0 0 0 0 0 0 0 0 0 0 ...
R> 

And because 2d is so common you can then do other things:

R> M <- as.matrix(m[, 2, ] )
R>

where we have

R> str(M)                                 # as before
 num [1:20, 1:2000] 0 0 0 0 0 0 0 0 0 0 ...
R> is.matrix(M)
[1] TRUE
R> is.matrix(m)
[1] FALSE
R> 

Upvotes: 3

Related Questions