Home > front end >  How to get the column names between two columns in R
How to get the column names between two columns in R

Time:03-09

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!

CodePudding user response:

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

CodePudding user response:

Without additional packages.

names_between <- function(col_1, col_2, data){
  names(data)[which(names(data) == col_1): which(names(data) == col_2)]
  }

names_between("Q1", "Q5", data = DF.1)
[1] "Q1" "Q2" "Q3" "Q4" "Q5"

CodePudding user response:

Using grep and seq.int.

f <- function(cn1, cn2, data) {
  pat <- paste(paste0('^', c(cn1, cn2), '$'), collapse='|')
  g <- grep(pat, colnames(data))
  colnames(data)[do.call(seq.int, as.list(g))]
}

f("Q1", "Q5", data=DF.1)
# [1] "Q1" "Q2" "Q3" "Q4" "Q5"
  • Related