-1

I am trying to order rows by a variable. I have created a sample data frame below and tried to order the rows but the ordering does not appear to work.

# Create vectors for data frame
score <- rep(seq(1:3), 2)
id <- rep(c(2014, 2015), each = 3)
var_if_1 <- rep(c(0.1, 0.8), each = 3)
var_if_2 <- rep(c(0.9, 0.7), each = 3)
var_if_3 <- rep(c(0.6, 0.2), each = 3)

# Generate and print data frame of raw data
foo <- data.frame(score, id, var_if_1, var_if_2, var_if_3)
foo

# Impose arbitrary ordering
bar <- foo[sample(1:nrow(foo)), ]
bar

# Order rows increasing on 'score'
bar[order(score), ]

What am I doing wrong that this doesn't oder the rows on score?

socialscientist
  • 3,759
  • 5
  • 23
  • 58

1 Answers1

2

You should use

bar[order(bar$score), ]

Otherwise, you're ordering on the base of the variable "score" instead of the column.

Michele Usuelli
  • 1,970
  • 13
  • 15