-2

For some reason using the order function is removing columns in my dataframe if it has 2 rows or less.

> coredf2
state start end
1  core     3   0
2  core     1   2

> coredf2[order('end')]
state
1  core
2  core
> coredf2[-order('end')]
start end
1     3   0
2     1   2

>stateList
state start end
1  core     1   4
2  core     7  10

>stateList[order(stateList[, 'start'])]
state start
1  core     1
2  core     7

Is this an intended effect? I don't want to write a special exception for 2 or less rows so is there something that doesn't suffer from this?

A D
  • 195
  • 5
  • 20

2 Answers2

3

Your syntax for sorting a data.frame is not correct. Here an example for sorting coredf2 by column end in descending order:

coredf2 <- data.frame(state = "core", start = c(3 ,1), end = c(0, 2))
coredf2[order(-coredf2$end), ]
#>   state start end
#> 2  core     1   2
#> 1  core     3   0
Ralf Stubner
  • 26,263
  • 3
  • 40
  • 75
1

The dplyr solution is very simple as well:

library(dplyr)
coredf2 <- data.frame(state = "core", start = c(3 ,1), end = c(0, 2))
arrange(coredf2, desc(end))
icj
  • 719
  • 6
  • 12