refer to range of columns by name in R

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

    You can call the column numbers by their names:

    set.seed(1234)
    > mydf <- data.frame(A = runif(5, 1, 2),
                         + B = runif(5, 3, 4),
                         + C = runif(5, 5, 6),
                         + D = runif(5, 7, 8),
                         + E = runif(5, 9, 10))
    > mydf
    mydf[c(match("A", names(mydf)):match("B", names(mydf)))]
             A        B
    1 1.113703 3.640311
    2 1.622299 3.009496
    3 1.609275 3.232551
    4 1.623379 3.666084
    5 1.860915 3.514251
    

    Here you can see that the match()-call actually gives the column number:

    > c(match("A", names(mydf)):match("B", names(mydf)))
    [1] 1 2
    

    I hope this is also helpful, it is similar to Neal's answer.

提交回复
热议问题