Select multiple columns with dplyr::select() with numbers as names Select multiple columns with dplyr::select() with numbers as names r r

Select multiple columns with dplyr::select() with numbers as names


Column names starting with a number, such as "1" and "8" in your data, are not syntactically valid names (see ?make.names). Then see the 'Names and Identifiers' section in ?Quoutes: "other [syntactically invalid] names can be used provided they are quoted. The preferred quote is the backtick".

Thus, wrap the invalid column names in backticks (`):

dd %>% dplyr::select(a:f, `1`:`8`)#           a        a2         b        b2          f         1         4         8# 1 0.2510023 0.4109819 0.6787226 0.4974859 0.01828614 0.7449878 0.1648462 0.5875638

Another option is to use the SE-version of select, select_:

dd %>% dplyr::select_(.dots = c("a", "a2", ..., "1", "4", "8"))


We can select columns a:f, and add index of numeric columns by converting colnames to numeric:

dd %>%   select(a:f, which(!is.na(as.numeric(colnames(dd)))))