Selecting multiple odd or even columns/rows for dataframe

I wish to add the tidyverse style approach to this problem, using the %% operator.

library(dplyr)
df <- data.frame(V1 = seq(26), V2 = letters)

df %>% filter(row_number() %% 2 == 0) ## Select even rows
df %>% filter(row_number() %% 2 == 1) ## Select odd rows
df %>% filter(row_number() %% 3 == 1) ## Select every 3rd row starting from first row

You can use the same idea to delete every n-th row, of course. See here.


When logical vectors are used for indexing, they are recycled so this gets you odd columns or odd rows

 calld[ c(TRUE,FALSE), ]  # rows
 calld[ , c(TRUE,FALSE) ] #columns

Even rows or columns:

 calld[ !c(TRUE,FALSE), ]  # rows
 calld[ , !c(TRUE,FALSE) ] #columns

Every third column:

  calld[ , c(TRUE,FALSE, FALSE) ]   #columns 1,4,7 , ....

A recent commenter claims this no longer works. I'm not finding that in R 4.0.4 running in Ubuntu:

> d <- data.frame(as.list(1:10))  # simple example construction
> d
  X1L X2L X3L X4L X5L X6L X7L X8L X9L X10L
1   1   2   3   4   5   6   7   8   9   10
> d[, c(TRUE,FALSE)]
  X1L X3L X5L X7L X9L
1   1   3   5   7   9
> d[, c(TRUE,FALSE,FALSE)]  # example: # of columns not exact multiple of length of logical vector
  X1L X4L X7L X10L
1   1   4   7   10

You can always generate sequences with seq:

even_indexes<-seq(2,42,2)
odd_indexes<-seq(1,41,2)

Then,

  x.loadings <- data.frame(x=data.pc$loadings[odd_indexes,1])

Tags:

R

Dataframe

Pca