Extracting Every Nth Element of A Matrix

时间:2015-07-14 19:33:46

标签: r matrix seq

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

1 个答案:

答案 0 :(得分:3)

你过度复杂了:

这可以满足您的需求

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

或更常见的

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