2

I have a data frame like this:

dataset <- data.frame(COL1 = c(1,2,3,4), COL2 = c(4,3,2,1))

I'm then trying to order it like so:

dataset <- dataset[order(-COl1),]

However, this results in an error because apparently COL1 doesn't exist:

Error in order(-COl1) : object 'COl1' not found

If I change the declaration of the dataset to:

dataset <- data.frame(COL1 <- c(1,2,3,4), COL2 <- c(4,3,2,1))

It works fine! However, the problem is that the dataset declaration is generated by another program so i cannot change it. Is there a way to re-declare the data set in a way that will allow me to order it properly?

Jaap
  • 81,064
  • 34
  • 182
  • 193
user1578653
  • 4,888
  • 16
  • 46
  • 74
  • You could use `with` or `$` `dataset[with(dataset, order(-COL1)),]`. BTW, you didn't have a column `COl1`, it is `COL1` (perhaps a typo) – akrun Jan 08 '15 at 17:34
  • @akrun Perfect! That worked - thanks for the prompt answer. If you want to add it as an answer I'll mark it as correct! – user1578653 Jan 08 '15 at 17:38
  • an alternative might be `library(dplyr); dataset <- arrange(dataset, desc(COL1))`or incl `library(magrittr); dataset %<>% arrange(desc(COL1))` but here of course this is too much overhead – ckluss Jan 08 '15 at 18:05

1 Answers1

1

You can use with or $, [, i.e.

dataset[with(dataset, order(-COL1)),] 

Or

dataset[order(-dataset$COL1),]

Or

dataset[order(-dataset['COL1']),]

Or

library(data.table)
setorder(setDT(dataset), -COL1)
akrun
  • 874,273
  • 37
  • 540
  • 662