简体   繁体   中英

call variables by name and column number in a data.frame

I have a data frame with columns I want to reorder. However, in different iterations of my script, the total number of columns may change.

>Fruit
Vendor A B C D E ... Apples Oranges
Otto   4 5 2 5 2 ... 3      4

Fruit2<-Fruit[c(32,33,2:5)]

So instead of manually adapting the code (the columns 32 and 33 change) I'd like to do the following:

Fruit2<-Fruit[,c("Apples", "Oranges", 2:5)]

I tried a couple of syntaxes but could not get it to do what I want. I know, this is a simple syntax issue, but I could not find the solution yet. The idea is to mix the variable name with the vector to reference the columns when writing a new data frame. I don't want to spell out the whole vector in variable names because in reality it's 30 variables.

I'm not sure how your data is stored in R, so this is what I used:

Fruit <- data.frame( "X1" = c("A",4),"X2" = c("B",5),"X3" = c("C",2),"X4"= 
c("D",5),"X5"= c("E",2),"X6" = c("Apples",3),"X7"= 
c("Oranges",4),row.names = c("Vendor","Otto"),stringsAsFactors = FALSE)

           X1 X2 X3 X4 X5     X6      X7
    Vendor  A  B  C  D  E Apples Oranges
    Otto    4  5  2  5  2      3       4

Then use:

indexes <- which(Fruit[1,]%in%c("Apples","Oranges"))
Fruit2<- Fruit[,c(indexes,2:5)]

Fruit[1,] references the Vendor row, and "%in%" returns a logical vector to the function "which". Then "which" returns indexes.

This gives:

    > Fruit2
               X6      X7 X2 X3 X4 X5
    Vendor Apples Oranges  B  C  D  E
    Otto        3       4  5  2  5  2

Make sure your data are not being stored as factors, otherwise this will not work. Or you could change the Vendor row to column names as per the comment above.

The answer is, as I found out, use the dplyr package. It is very powerful.

The solution to the aforementioned problem would be:

Fruit2<-Fruit %>% select(Apples,Oranges,A:E)

This allows dynamic selection of columns and lists of columns even if the indexes of the columns change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM