date
Another way to do this is to use the xtfrm() function. That function creates numerical values from many different starting types, so you can just change the sign to change the sort order: df[order(df$ID, -xtfrm(df$date2)),] I never did figure out where the name came from. Duncan Murdoch
On 21/09/2020 3:41 p.m., Sarah Goslee wrote:
Hi, Nice reproducible example. rev(df$date2) isn't doing what you think it's doing - try looking at it by itself. Some digging into ?order will get you what you are after: df[order(df$ID, df$date2, decreasing=c(FALSE, TRUE), method="radix"),]
df[order(df$ID, df$date2, decreasing=c(FALSE, TRUE), method="radix"),]
ID date2 2 A1 2005-01-27 1 A1 2004-09-17 3 A1 2003-05-07 4 A2 2017-05-21 5 A2 2016-09-12 6 A3 2013-01-25 7 A4 2019-09-27 Sarah On Mon, Sep 21, 2020 at 2:41 PM Val <valkremk at gmail.com> wrote:
Hi All, I am trying to sort dates within a group. My sample data is df <-read.table(text="ID date A1 09/17/04 A1 01/27/05 A1 05/07/03 A2 05/21/17 A2 09/12/16 A3 01/25/13 A4 09/27/19",header=TRUE,stringsAsFactors=F) df$date2 = as.Date(strptime(df$date,format="%m/%d/%y")) df$date =NULL I want to sort date2 from recent to oldest. within the ID group and I used this, df <- df[order(df$ID, rev((df$date2))),]. It did not work and teh output is shown below. ID date2 2 A1 2005-01-27 3 A1 2003-05-07 1 A1 2004-09-17 5 A2 2016-09-12 4 A2 2017-05-21 6 A3 2013-01-25 7 A4 2019-09-27 What am I missing? Thank you.
______________________________________________ R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.