-3

I tried to sort the following data frame. But I get error like

sort(test,decreasing = TRUE)

Error in [.data.frame(x, order(x, na.last = na.last, decreasing = decreasing)) : undefined columns selected"

   test <- data.frame(x = c(26, 21, 20), y = c(34, 29, 28))
   sort(test$y,decreasing = TRUE)
   [1] 34 29 28

But I need

    x  y
 1 20 28
 2 21 29
 3 26 34
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
Jana P
  • 25
  • 5

2 Answers2

2

We can use order to get the index and use that to order to rows of data

test[order(test$y),]
#   x  y
#3 20 28
#2 21 29
#1 26 34

sort returns the sorted values. If we need the index as well, use index.return = TRUE (by default it is FALSE), then it would return a list of vectors - values and 'ix' for the index. Extract the index and use for ordering

akrun
  • 874,273
  • 37
  • 540
  • 662
1

You need decreasing as FALSE not TRUE:

test[sort(test$y, decreasing = FALSE,index.return=TRUE)[[2]],]
   x  y
3 20 28
2 21 29
1 26 34
NelsonGon
  • 13,015
  • 7
  • 27
  • 57