Home > Enterprise >  sort two column values ​by date in R
sort two column values ​by date in R

Time:08-25

I have a dataframe where I have two columns with names

df1 <- structure(list(Col1 = c("Luis", "Pedro", "John", "Ingrid"), 
                      Col2 = c("Raul", "Maria", "Chris", "Lia")), 
                 class = "data.frame", row.names = c(NA, -4L))

and I have another one with dates corresponding to each name:

df2 <- structure(list(Name = c("Luis", "Pedro", "John", "Ingrid","Raul", "Maria", "Chris", "Lia"),
                      Date = c("10/05/22","04/05/22", "03/05/22", "07/05/22","01/05/22","06/05/22", "05/05/22","02/05/22")), 
                 class = "data.frame", row.names = c(NA, -8L))

it looks like this:

df1:

    Col1  Col2
1   Luis  Raul
2  Pedro Maria
3   John Chris
4 Ingrid   Lia

df2:

    Name     Date
1   Luis 10/05/22
2  Pedro 04/05/22
3   John 03/05/22
4 Ingrid 07/05/22
5   Raul 01/05/22
6  Maria 06/05/22
7  Chris 05/05/22
8    Lia 02/05/22

what I want is that in each row, the name with the date that goes first appears in the first column, and in the second the name that has the later date, I put an example of the result that I expect:

    Col1  Col2
1   Raul  Luis
2  Pedro Maria
3   John Chris
4    Lia Ingrid

CodePudding user response:

We convert the 'Date' to Date class and do the ordering

df2$Date <- as.Date(df2$Date, "%d/%m/%y")
df2new <- df2[order(df2$Date),]
df1[] <-  t(apply(df1, 1, function(x) x[order(match(x, df2new$Name))]))

-output

> df1
   Col1   Col2
1  Raul   Luis
2 Pedro  Maria
3  John  Chris
4   Lia Ingrid
  •  Tags:  
  • r
  • Related