-2

I have three files containing weight, names and wins. I put them into 3 data.frames (held in one list). I am trying to get the 10 highest weights and the corresponding row's values in names and wins.

I know that there is a sort function, but if I sort, I lose the element for the corresponding row number of weight and wins. How am I able to get the highest elements as well as the corresponding rows in the other two lists?

I looked into creating one data.frame with three different columns(weight,names,wins), but I am unsure how to do that.

my.path <- list( "weights.csv","names.csv", "wins.csv")
my.data <- lapply(my.path, read.csv)

my.path2 <- list( "weights.csv","names.csv", "wins.csv")
my.d <- lapply(my.path, read.csv)

#newdata <- my.data[order(my.data[2])] 
#print(newdata)
#lapply(my.data[1], function(x) x[order(x), ])

print(my.data[1])
zx8754
  • 42,109
  • 10
  • 93
  • 154
  • The OP is also asking about how to get the data into a single data.frame. Not quite a duplicate, though there is some overlap. – Jason Oct 16 '16 at 09:50
  • 2
    [How to make a great R reproducible example?](http://stackoverflow.com/questions/5963269) – zx8754 Oct 16 '16 at 12:04

1 Answers1

3

I'd use c() for the file names, not a list(). An R list is more typically used for when you have a collection of data objects, e.g. a set of vectors or data.frames. Using this convention means I'm less confused about my intentions when I have to read my code months later.

Like this:

my.path <- c( "weights.csv","names.csv", "wins.csv")
my.data <- lapply(my.path, read.csv)

At this point, you have one list (my.data) which contains three data.frames, presumably with one column each (I don't know; I haven't seen your data). Normally, we want them all in one data.frame, like so:

my.data <- data.frame(my.data)
names(my.data) <- c("weights", "names", "wins")

Because the separate lists are now joined in one data.frame, ordering the data.frame by weights will now correctly re-order "names" and "wins". Also remember: order() does not re-order the data. Compare its help page with that of sort().

my.data.sorted <- my.data[order(my.data$weights, decreasing=TRUE), ]

To get the 10 highest weights and the corresponding names and wins values:

my.data.sorted[1:10, ]
zx8754
  • 42,109
  • 10
  • 93
  • 154
Jason
  • 2,177
  • 16
  • 25