Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We can use match with seqmatch 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading