0

I have a R dataframe and I need to select first n columns and some other columns using name.

Can I do it in a single statement ?

Say I need to choose columns from 1 to 10 and columns named as A,B,C etc

1 Answer 1

3

select from dplyr allows to do that.

library(dplyr)
mtcars %>% select(1:3, 'am', 'carb') %>% head

#                   mpg cyl disp am carb
#Mazda RX4         21.0   6  160  1    4
#Mazda RX4 Wag     21.0   6  160  1    4
#Datsun 710        22.8   4  108  1    1
#Hornet 4 Drive    21.4   6  258  0    1
#Hornet Sportabout 18.7   8  360  0    2
#Valiant           18.1   6  225  0    1

In base R, you can use either index or names at a given time, so you can either do :

mtcars[, c(names(mtcars)[1:3], 'am', 'carb')]

Or :

mtcars[, c(1:3, match(c('am', 'carb'), names(mtcars)))]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.