refer to range of columns by name in R

后端 未结 6 1703
暗喜
暗喜 2020-12-17 04:00

I need help with something that might be fairly simple in R. I want to refer to a range of columns in a data frame (e.g., extracting a few select variables). However, I don\

6条回答
  •  既然无缘
    2020-12-17 04:52

    Here is a fun little function that combines the ideas behind Largh's answer with a handy function call. To use it, just enter

    call.cols(mydata, "firstvarname", "lastvarname")

    call.cols <- function(df, startvar, endvar) {
      col.num <- function(df){
        var.nums <- seq(1,ncol(df))
        names(var.nums) <- colnames(df)      
        return(var.nums)
      } 
    
     start.num <- as.numeric(col.num(df)[startvar])
     end.num <- as.numeric(col.num(df)[endvar])
     range.num <- start.num:end.num
     return(df[range.num]) 
    }
    

    I plan to expand this to use for scale creation for psychometric research.

提交回复
热议问题