Search code examples
rseq

Select every nth column in R from position x


Imagine data is

v1<-c(1,2,3)
v2<-c(3,1,2)
v3<-c(5,4,3)
v4<-c(2,3,2)
v5<-c(6,2,1)
v6<-c(1,1,2)
v7<-c(2,2,1)
mydata<-data.frame(v1,v2,v3,v4,v5,v6,v7)

I would like every other column from position v3.

  v3 v5 v7
1  5  6  2
2  4  2  2
3  3  1  1

I am not sure how to use seq() from a certain position instead of the starting from the first column.


Solution

  • We can use match with seq - match returns the position index of the column name that matches the 'v3', then use seq with by as 2 and to as the index of last column (ncol)

    mydata[seq(match('v3', names(mydata)), ncol(mydata), by = 2)]
    

    -output

      v3 v5 v7
    1  5  6  2
    2  4  2  2
    3  3  1  1
    

    Or in dplyr with num_range

    library(dplyr)
    mydata %>% 
       select(num_range(prefix = "v", range = seq(3, last_col(), by = 2)))
    

    -output

      v3 v5 v7
    1  5  6  2
    2  4  2  2
    3  3  1  1