0

Setup dataframe

mta<-c("ldall","nold","ldall","nold","ldall","nold","ldall","nold")
mtb<-c(491, 28581,241,5882,365,7398,512,10887)
df1<-data.frame(mta,mtb)

I can order my dataframe in the normal way. This works fine.

df1[order(mtb),]

But if I change the names of the columns

names(df1)<-c("mta1","mtb1")
df1[order(mtb1),]

This gives the error

Error in order(mtb1) : object 'mtb1' not found.

If I use the old column name in the instruction it works, although the output shows the new column name.

df1[order(mtb),]

If I change the name back to the original, the command appears to work normally. Can anyone explain? Is order using a hidden version of the column name?

aynber
  • 22,380
  • 8
  • 50
  • 63
  • 1
    `mtb` works because you have it defined as a vector in your global environment. `mtb1` on the other hand is just a column in your data frame. So what you need is `df1[order(df1$mtb1),]` – Sotos Nov 18 '17 at 11:35

1 Answers1

0

This should work. Let me know if this helps.

mta<-c("ldall","nold","ldall","nold","ldall","nold","ldall","nold")
mtb<-c(491, 28581,241,5882,365,7398,512,10887)
df1<-data.frame(mta,mtb)

# Change column names
colnames(df1) <- c("mta1","mtb1")

# Sort column mtb1 from the data frame
df1[order(df1$mtb1), ]

   mta1  mtb1
3 ldall   241
5 ldall   365
1 ldall   491
7 ldall   512
4  nold  5882
6  nold  7398
8  nold 10887
2  nold 28581
Code_Sipra
  • 1,571
  • 4
  • 19
  • 38