refer to range of columns by name in R

后端 未结 6 1736
暗喜
暗喜 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:47

    Getting a range of columns can be done in several ways. subset(data.frame, select = name4:name10), works but is quite long. I used that before I got annoyed writing long commands for a simple thing. I made a function to tackle the naming columns / not remembering column numbers in large data frames:

    coln <- function(X){
      y <- rbind(seq(1,ncol(X)))
      colnames(y) <- colnames(X)
    rownames(y) <- "col.number"
      return(y)} 
    

    Here is how it works:

    df <- data.frame(a = 1:10, b =10:1, c = 1:10)
    coln(df)
               a b c
    col.number 1 2 3
    

    Now you can call them with numbers and still look at names.

提交回复
热议问题