Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reorder columns in dataframe by last value in each column in R

Tags:

r

dplyr

it's my first question, happy to be here :) So i've got a dataframe, for example:

date <- as.Date(c('2019-03-1','2019-4-25','2019-5-25','2019-6-14','2019-7-14','2019-8-15'))
US <- c(340, 450, 100, 400, 500, 350)
JP <- c(600, 700, 400, 600, 500, 700)
CHN <- c(400, 550, 450, 600, 200, 300)
GER <- c(800, 900, 700, 700, 600, 900)
IT <- c(400, 500, 350, 600, 600, 500)
BR <- c(300, 400, 450, 300, 450, 250)

df <- data.frame(date, US, JP, CHN, GER, IT, BR)

which gives

      startdate  US  JP CHN GR  IT  BR
1   2019-03-01  340 600 400 800 400 300
2   2019-04-25  450 700 550 900 500 400
3   2019-05-25  100 400 450 700 350 450
4   2019-06-14  400 600 600 700 600 300
5   2019-07-14  500 500 200 600 600 450
6   2019-08-15  350 700 300 900 500 250

what I want, is to change order of the columns in this dataframe so that country with the highest value at the last date ( in this case "2019-08-15") would be the second column, country with the second highest value at the last date would be the third column, and so on. It's just about the last value, not earlier dates. Just like here:


      startdate  GR  JP  IT US  CHN  BR
1   2019-03-01  800 600 400 340 400 300
2   2019-04-25  900 700 500 450 550 400
3   2019-05-25  700 400 350 100 450 450
4   2019-06-14  700 600 600 400 600 300
5   2019-07-14  600 500 600 500 200 450
6   2019-08-15  900 700 500 350 300 250

Trying to figure it out for two days now and got nowhere. Please help :)

like image 211
h4rves7er Avatar asked Dec 23 '22 19:12

h4rves7er


1 Answers

A base R option would be to get the last row of the dataframe and order them based on values in them. While ordering we ignore the date column.

df[c(1, order(-df[nrow(df), -1]) + 1)]

#        date GER  JP  IT  US CHN  BR
#1 2019-03-01 800 600 400 340 400 300
#2 2019-04-25 900 700 500 450 550 400
#3 2019-05-25 700 400 350 100 450 450
#4 2019-06-14 700 600 600 400 600 300
#5 2019-07-14 600 500 600 500 200 450
#6 2019-08-15 900 700 500 350 300 250
like image 62
Ronak Shah Avatar answered May 01 '23 01:05

Ronak Shah