Chris
Chris

Reputation: 75

Sort list of dates and sort other list based on this sorting order in R

I've got a list of dates which are not in the correct order: "1-12-2019" "17-11-2019" "18-11-2019"

Besides this list of dates, I've also got a list of corresponding values: 2 3 2

I want to sort the dates list in the ascending order. And in the same order that the dates list is sorted, I want to sort the values list.

For example:

Current situation:

Wanted situation:

Would appreciate it if I could get some help.

Upvotes: 0

Views: 524

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102171

Maybe you can try the following code

res <- as.numeric(names(sort(setNames(as.Date(s, format = '%d-%m-%Y'),c(2,3,2)))))

such that

> res
[1] 3 2 2

DATA

s <- c("17-11-2019", "18-11-2019", "1-12-2019")

Upvotes: 0

Sotos
Sotos

Reputation: 51592

You just need to order your dates and use them as index to order the values, i.e.

i1 <- order(as.Date(datesLst, format = '%d-%m-%Y'))
datesLst[i1]
#[1] "17-11-2019" "18-11-2019" "1-12-2019" 
valueslist[i1]
#[1] 3 2 2

Upvotes: 3

Related Questions