The select()
function from dplyr is powerful for subsetting columns. See ?select_helpers
for a list of approaches.
In this case, where you have a common prefix and sequential numbers for column names, you could use num_range
:
library(dplyr)
df1 <- data.frame(first = 0, col1 = 1, col2 = 2, col3 = 3, col4 = 4)
df1 %>%
select(num_range("col", c(1, 4)))
#> col1 col4
#> 1 1 4
More generally you can use the minus sign in select()
to drop columns, like:
mtcars %>%
select(-mpg, -wt)
Finally, to your question "is there an easy way to create a workable vector of column names?" - yes, if you need to edit a list of names manually, use dput
to get a comma-separated, quoted list you can easily manipulate:
dput(names(mtcars))
#> c("mpg", "cyl", "disp", "hp", "drat", "wt", "qsec", "vs", "am",
#> "gear", "carb")