How do I group the first four columns and the last four columns using Dplyr?

Viewed 34

I am working on an assignment where we are only allowed to used Dplyr in R. We have to print the first 4 columns and the last 4 columns with customers that have 10 or less Open Accounts. So far I have the following

OpenAccount <- filter(loans,OpenAccounts < 10,)

however, I am not sure how to only include the first four columns and the last 4 columns.

2 Answers

We can use select

library(dplyr)
OpenAccount %>%
      select(head(names(.), 4), tail(names(.), 4))

You can select columns using ncol :

n <- ncol(OpenAccount)
OpenAccount %>% select(1:4, (n - 3) :n)

For example, with mtcars dataset :

n <- ncol(mtcars)
mtcars %>% select(1:4, (n - 3) :n)

#                     mpg cyl  disp  hp vs am gear carb
#Mazda RX4           21.0   6 160.0 110  0  1    4    4
#Mazda RX4 Wag       21.0   6 160.0 110  0  1    4    4
#Datsun 710          22.8   4 108.0  93  1  1    4    1
#Hornet 4 Drive      21.4   6 258.0 110  1  0    3    1
#...
#...
Related