只是为了完整性的缘故。实际上这里不需要拨打seq
。你可以只使用:
-R逻辑:
### Create some sample data
n=252
sampledata<-data.frame(a=sample(letters,n,replace=TRUE),b=rnorm(n,1,0.7),
c=rnorm(n,1,0.6),d=runif(n))
### Compare some different ways to reorder the dataframe
myfun1<-function(df=sampledata){df<-df[seq(nrow(df),1),]}
myfun2<-function(df=sampledata){df<-df[seq(dim(df)[1],1),]}
myfun3<-function(df=sampledata){df<-df[dim(df)[1]:1,]}
myfun4<-function(df=sampledata){df<-df[nrow(df):1,]}
### Microbenchmark the functions
microbenchmark::microbenchmark(myfun1(),myfun2(),myfun3(),myfun4(),times=1000L)
Unit: microseconds
expr min lq mean median uq max neval
myfun1() 63.994 67.686 117.61797 71.3780 87.3765 5818.494 1000
myfun2() 63.173 67.686 99.29120 70.9680 87.7865 2299.258 1000
myfun3() 56.610 60.302 92.18913 62.7635 76.9155 3241.522 1000
myfun4() 56.610 60.302 99.52666 63.1740 77.5310 4440.582 1000
的最快的方式在我这里试验是使用df<-df[dim(df)[1]:1,]
。但是,使用nrow
而不是dim
仅稍微慢一些。这是个人喜好的问题。
使用seq
这里肯定会减慢过程。
来源
2017-09-25 06:39:53
5th
如果'df'是你的'data.frame',日期列被称为'date',并且你想按日期对数据集进行排序,只需尝试'df [order(df $ date),]'。 – nicola
还要确保你的'日期'列设置'as.Date' – Sotos
OP的日期不是'Date'对象,不幸的是@Sotos。如果是ISO格式的话,它会是。尽管我非常好奇为什么显示顺序很重要(因为我们可能能够帮助他们进行任何依赖于顺序的处理)。但是,由于OP似乎已经以相反的顺序使用了它,并且知道'df [252:1,]行的行号也可以工作。 – hrbrmstr