R: Addressing multiple columns of data frame by name

27,469

You can address them with names as you suspect, just pass the names through as a character vector:

partimat(MARKER ~ ., trim_data11[, c("AF3","F7","P8","O1","O2","MARKER") ],method="qda")

As a simple example:

df <- data.frame( x = runif(5) , y =runif(5) , z = runif(5) )
df[,c("x","z")]
#         x         z
#1 0.5896444 0.1855764
#2 0.3486369 0.4936727
#3 0.1640928 0.1367027
#4 0.3167399 0.6686943
#5 0.7063566 0.6032699
Share:
27,469
bright-star
Author by

bright-star

Updated on September 06, 2022

Comments

  • bright-star
    bright-star over 1 year

    I have some data sets with high enough dimension (14) to be painful to plot pairwise in one go. In that case I'd like to be able to select a subset of the dataframe they're in, but I only know how to address columns by number. This is irritating and unclear when the code is read back:

    partimat(MARKER ~ ., trim_data11[,c(1:5,NCOL(trim_data11))],method="qda")
    

    What I would like to do is something like this, which doesn't work:

    partimat(MARKER ~ ., trim_data11$(c(AF3,F7,P8,O1,O2,MARKER)),method="qda")
    

    Is there a way to do this?

  • Maxim.K
    Maxim.K about 11 years
    Note that this works too: df[c("x","z")] works too (but not with a matrix).
  • Simon O'Hanlon
    Simon O'Hanlon about 11 years
    @Maxim.K yes true, you only need to use the , if you want to subset by rows, but I always put it in anyway just as good practice. That way works because df is a named list, whereas a matrix is just a vector with a dim attribute of length 2.