jmn*_*mn8 23 sorting r dataframe
我无休止地寻找这个,不知何故没有解决这个简单的问题.
我有一个名为Price的数据框,其中有4列,其中一列是历史日期列表 - 另外3列是产品价格列表.
1 10/10/2016 53.14 50.366 51.87
2 07/10/2016 51.93 49.207 50.38
3 06/10/2016 52.51 49.655 50.98
4 05/10/2016 51.86 49.076 50.38
5 04/10/2016 50.87 48.186 49.3
6 03/10/2016 50.89 48.075 49.4
7 30/09/2016 50.19 47.384 48.82
8 29/09/2016 49.81 46.924 48.4
9 28/09/2016 49.24 46.062 47.65
10 27/09/2016 46.52 43.599 45.24
Run Code Online (Sandbox Code Playgroud)
这个名单是252个价格长.如何将我的输出存储在列表底部的最新日期以及列表底部的最新价格列出的相应价格中?
小智 12
如果您只想反转数据框中行的顺序,可以执行以下操作:
df<- df[seq(dim(df)[1],1),]
Run Code Online (Sandbox Code Playgroud)
5th*_*5th 10
只是为了完整起见.实际上没有必要在seq
这里打电话.你可以使用:
-R-logic:
### 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
Run Code Online (Sandbox Code Playgroud)
我在这里试用的最快方法是使用df<-df[dim(df)[1]:1,]
.但是使用nrow
而不是dim
仅略慢.这是个人偏好的问题.
seq
在这里使用肯定会减慢过程.
更新2018年9月:
从速度来看,没有理由在dplyr
这里使用.对于大约90%的用户来说,基本的R功能应该足够了.其他10%需要dplyr
用于查询数据库或需要将代码翻译成另一种语言.
## hmhensen's function
dplyr_fun<-function(df=sampledata){df %>% arrange(rev(rownames(.)))}
microbenchmark::microbenchmark(myfun3(),myfun4(),dplyr_fun(),times=1000L)
Unit: microseconds
expr min lq mean median uq max neval
myfun3() 55.8 69.75 132.8178 103.85 139.95 8949.3 1000
myfun4() 55.9 68.40 115.6418 100.05 135.00 2409.1 1000
dplyr_fun() 1364.8 1541.15 2173.0717 1786.10 2757.80 8434.8 1000
Run Code Online (Sandbox Code Playgroud)