refer to range of columns by name in R

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

    A column number can be identified from a column name within a data frame as follows:

    which(colnames(mydf)=="a")
    

    where mydf is a data frame and a is the name of the column the column number is required for.

    (Source)

    This can be used to create a column range:

    firstcol = which(colnames(x)=="a")
    lastcol = which(colnames(x)=="b")
    
    mydf[c(firstcol:lastcol)]
    

提交回复
热议问题