adkane
adkane

Reputation: 1441

In R how can I select every nth column and every nth row within those columns?

I have a large data set and I want to select every nth column and every nth row within that column.

In this example if I want every 2nd column and every 2nd row I would get 9 and 11 for the first and 6 and 8 for the second.

x <- data.frame("x1" = c(1:4), "y1" = c(8:11), "x2" = c(14:17), "y2" = c(5:8))
x

Upvotes: 0

Views: 4132

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388907

We can use vector recycling :

n <- 2
inds <- c(rep(FALSE, n - 1), TRUE)
x[inds, inds]

#  y1 y2
#2  9  6
#4 11  8

Upvotes: 0

dave-edison
dave-edison

Reputation: 3726

This works:

x[seq_len(nrow(x)) %% 2 == 0, seq_len(ncol(x)) %% 2 == 0]
#>   y1 y2
#> 2  9  6
#> 4 11  8

Upvotes: 4

Related Questions