rer
rer

Reputation: 1268

Order data.frame by row values in a column and by column values in a row in R

I have six cockatiel birds, "Beefy", "Scoundrel", "Baston", "Mattdamon", "Jesus", and "Hulkhogan". These birds poo a lot, and in a lot of different locations. I've decided to track where and how often this occurs over the last 2 weeks, and I'm trying to figure out where these little devils pooed the most today.

mydata <- data.frame(Dates = structure(c(16656, 16657, 16658, 16659,
                                         16660, 16661, 16662, 16663,
                                         16664, 16665, 16666, 16667,
                                         16668, 16669 
                                         ), 
                                       class = "Date"), 
                     PooLoc1 = sample(1:40, 7),
                     PooLoc2 = sample(1:10, 7),
                     PooLoc3 = sample(1:10, 7),
                     PooLoc4 = sample(1:30, 7),
                     PooLoc5 = sample(1:20, 7),
                     PooLoc6 = sample(1:70, 7)
)

head(mydata)
     Dates PooLoc1 PooLoc2 PooLoc3 PooLoc4 PooLoc5 PooLoc6
2015-08-09      24       3       9       1      16      45
2015-08-10      39       2       2      12      12       2
2015-08-11      14       7       6       5      19       4
2015-08-12      26       9       8      27       3      64
2015-08-13      20       4       1      15      20      48
2015-08-14       9       1       4       8       8      61

I can order mydata rows by column date to easily find today's poos like so:

mydata <- mydata[order(mydata[["Dates"]], decreasing = TRUE), ]

But how do I order the columns by the values obtained on today's date so that I can quickly look at the top left of mydata and find the answer to my question? Can you do it in one line?

Upvotes: 2

Views: 105

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99391

I think this may be what you want. We just order the columns (second to end) by the first row.

mydata[, c(1, order(mydata[1, -1], decreasing = TRUE) + 1)]
#        Dates PooLoc6 PooLoc1 PooLoc4 PooLoc5 PooLoc3 PooLoc2
# 6 2015-08-14      61       9       8       8       4       1
# 5 2015-08-13      48      20      15      20       1       4
# 4 2015-08-12      64      26      27       3       8       9
# 3 2015-08-11       4      14       5      19       6       7
# 2 2015-08-10       2      39      12      12       2       2
# 1 2015-08-09      45      24       1      16       9       3

Now the top left value has the highest value for today's date.

And per the request in the comments, we can order the rows and columns in one call with

mydata[
    order(mydata$Dates, decreasing = TRUE), 
    c(1, order(mydata[1, -1], decreasing = TRUE) + 1)
]

Upvotes: 3

Related Questions