Selecting multiple odd or even columns/rows for dataframe

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

Leave a Comment