Search code examples
rdataframedata-management

How to get the column names between two columns in R


Is there a function in R that returns the names of columns, including and between two column names? This function would take the beginning column and the ending columns as inputs and return the names of the columns between and including the inputs.

For example, say I am using the following data frame:

set.seed(1993)
DF.1 <- data.frame("Q0"= sample(seq(1,100), replace = T, 100))
for(i in seq(1,50, by =1)){
  
  x <-sample(seq(1,100), replace = T, 100)
  DF <- data.frame(x)
  
  names(DF)[names(DF) == "x"] <- paste("Q", i, sep = "")
  
  DF.1 <- cbind(DF.1, DF)
  
}

colnames(DF.1)

A potential function might look like this

function(Column Name 1, Column Name 2, data)
function("Q1", "Q5", data = DF.1)

And it would output:

>"Q1"  "Q2"  "Q3"  "Q4"  "Q5"

Note: that the function would need to be generalizable to any set of column names.

Thank You!


Solution

  • You can use the dplyr package like this:

    library(dplyr) 
    df %>% select(Q1:Q5) %>% colnames() 
    

    or as function:

    find_colnames <- function(c1, c2, data) data %>% select(c1:c2) %>% colnames()