只是爲了完整性的緣故。實際上這裏不需要撥打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