I am new to R and hence my question is likely to be basic. I tried researching the answer before posting here however didn't get the answer I was looking for.

I am trying to order a data frame on the basis of certain columns. The column is dynamic and depends on a certain "outcome" which would be from a vector of "validoutcomes".

validoutcomes <- c("A","B","C")

if outcome is "A" then I am supposed to read data from column 11. For "B" its columns 17 and for "C" it is 23.

I renamed the columns so that it is easier for my readability and alignment with validoutcomes. "input" is my source data from the CSV.

colnames(input)[11] <- validoutcomes[1] colnames(input)[17] <- validoutcomes[2] colnames(input)[23] <- validoutcomes[3]

I then tried to sort using

statelist <- statelist[order(statelist$outcome)]

Any ideas?


2 Answers 2


Your first attempt was more accurate. Since I do not have your data I will just use the iris data set,

 iris_ordered_on_Sepal_Length <- iris[order(iris$Sepal.Length),]

or if you use data.table,

iris_dt <- data.table(iris)

data.table will make renaming easier too,

setnames(input, c("colname_11, "colname_17", "colname_23"), validoutcomes[1 : 3])

Ok, I have found the likely answer. I am not sure if this is the best answer but it worked for me.

Since $ is used to call the colnames, R was looking for a column name as outcome. However all it needed was square brackets[]. I replaced it and so far seems to be working for me.

statelist <- statelist[order(statelist[outcome])]

I am still very interested in knowing if there is a better solution or if someone sees issue with my observation.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.