Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder dataframe columns while ignoring unidentified columns

Tags:

dataframe

r

I'm thinking there's got to be a better way to do this.

I'm trying to reorder the columns in a dataframe. I have a list, ordered.colnames, representing the new ordering -- but some of the columns don't exist in dataset. To avoid the Error "undefined columns selected", I've wrapped the relevant slicing in a try() function.

The following method works, but is there a better way to do this?

> ordered.colnames[1:5]
[1] "lady_22102"         "attentions_83249"   "perseverance_17864"
[4] "cecil_84477"        "cecilia_133476"

dataset.reordered = c() 
for (i in 1:length(ordered.colnames)) {
    col = NA
    col = try(cbind(dataset[,ordered.colnames[i]]),silent=TRUE)
    if (!inherits(col,"try-error")) {
        colnames(col) = ordered.colnames[i]
        dataset.reordered = cbind(dataset.reordered, col) 
    }
}
like image 287
ariddell Avatar asked Oct 08 '09 16:10

ariddell


1 Answers

Can't you just do this?

ordered.colnames <- ordered.colnames[ordered.colnames %in% colnames(dataset)]
like image 75
Shane Avatar answered Nov 29 '22 20:11

Shane