在R中按降序订购日期/时间 [英] Ordering date/time in descending order in R

查看:67
本文介绍了在R中按降序订购日期/时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框DF,其中一列为日期/时间,我想按此列的降序对数据框进行排序。

I have a data frame DF with one of the columns being date/Time and I would like to order the data frame in descending order of this column.

DF <- data.frame(ID=c('ID3', 'ID2','ID1'), end=c('4/1/10 12:00', '6/1/11 14:20', '1/1/09 11:10'), age=c(40,30,20));

我首先将 end 列转换为 et 使用 et = as.POSIXct(DF $ end,format ='%m /%d /%Y%H:%M'),并使用了以下内容,但得到的错误是参数不接受一元运算符-:

I first converted the end column into et using et = as.POSIXct(DF$end,format='%m/%d/%Y %H:%M'), and used the following, but got the error that unary operator '-' is not accepted for the argument :

out <- DF[order(-DF$et),];

我也尝试使用降序标志,但又收到关于参数长度不相同的错误。 / p>

I also tried used the descending flag but again got an error about arguments not being of same length.

out <- DF[order(DF$et, descending=TRUE),];

但是,升序似乎有效: out<-DF [ order(DF $ et),]

However, the ascending order seems to work: out <- DF[order(DF$et),].

如何按降序排列(最近的时间在前)?谢谢。

How can I order in descending order (most recent time first)? Thank you.

推荐答案

对于您的问题,有一个简单而通用的解决方案,只需很少的代码。

There is an easy and general solution for your issue with few code.

您已经注意到,负号不适用于Dates,因为尚不存在负日期!

As you have noticed, the minus sign doesn't work with Dates because negative dates don't yet exist!

但是您可以使用与通用函数相同的效果:rev()。因此,您将rev和order混合使用:

However you can have the same effect with a general purpose function: rev(). Therefore, you mix rev and order like:

#init data
DF <- data.frame(ID=c('ID3', 'ID2','ID1'), end=c('4/1/10 12:00', '6/1/11 14:20', '1/1/09 11:10')
#change order
out <- DF[rev(order(as.Date(DF$end))),]

当您对数字使用减号时,您会在一遍中对负数进行分类。我认为当您使用rev()函数时,您将进行两遍,一遍

When you use the minus sign with numbers you are classing negative numbers in one pass. I think that when you use rev() function, you are doing two passes, one to sort in ascending order and one for reversing the order. But on 3 observations, it's hard to see.

希望它有帮助。

这篇关于在R中按降序订购日期/时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆