Adam Warner
Adam Warner

Reputation: 1354

Extracting Every Nth Element of A Matrix

I want to extract every nth element of row for each row in a matrix, here is my code:

x <- matrix(1:16,nrow=2)
x
       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    3    5    7    9   11   13   15
[2,]    2    4    6    8   10   12   14   16

I have tried:

sapply(x, function(l) x[seq(1,8,2)]) 

which clearly fails.

I want to pull every 2nd value from "x" the desired output would be something like...

      [,1] [,2] [,3] [,4]
[1,]    3    7   11   15
[2,]    4    8   12   16

Upvotes: 2

Views: 6370

Answers (1)

nico
nico

Reputation: 51690

You are overcomplicating it:

This gives you what you need

x[,seq(2, 8, 2)]

or, more generally

x[,seq(2, ncol(x), 2)]

Upvotes: 4

Related Questions