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)
}
}