Victor Johnzon
Victor Johnzon

Reputation: 225

selecting specific columns from R datatable

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

Upvotes: 0

Views: 58

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388807

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)))]

Upvotes: 3

Related Questions