简体   繁体   English

在R中对数据框的特定行进行排序

[英]Sorting specific rows of a dataframe in R

Data:- 数据:-

df:-

    Name       Date
1    A     2015-01-01
2    B     2016-05-01
3    B     2015-01-05
4    A     2015-12-25
5    C     2015-01-01

Code:- 码:-

df <- df[order(df[,c("Name")]),]
> df
  Name       Date
1    A 2015-01-01
4    A 2015-12-25
2    B 2016-05-01
3    B 2015-01-05
5    C 2015-01-01
index= which(df$Name=="B")
start= index[1]
end=index[length(index)]
df[start:end,] <- df[order(df[start:end,("Date")]),]

> df
   Name       Date
1    A    2015-01-01
4    A    2015-12-25
2    A    2015-12-25
3    A    2015-01-01
5    C    2015-01-01

As one can see this is not the output I was expecting. 可以看到,这不是我期望的输出。 I sort the dataframe first by Name ,which works well and then I try to sort the individual rows of specific names. 我先按Name对数据框进行排序,这很好用,然后尝试对特定名称的各个行进行排序。 I find the starting and ending index of a particular name and try to sort the specific rows by Date . 我找到了特定名称的开始和结束索引,并尝试按Date对特定行进行排序。 Second sorting leads to this error output. 第二次排序导致此错误输出。 Please advice , also is there any shorter method for this? 请指教,还有没有更短的方法呢? Thanks in advance. 提前致谢。

Expected Output:- 预期产量:-

Name       Date
1    A 2015-01-01
4    A 2015-12-25
3    B 2015-01-05 
2    B 2016-05-01
5    C 2015-01-01

It appears that you do not yet understand that order can take both primary and secondary sort vectors: 似乎您还不了解order可以同时使用主要和次要排序向量:

> df1 <- read.table(text="    Name       Date
+ 1    A     2015-01-01
+ 2    B     2016-05-01
+ 3    B     2015-01-05
+ 4    A     2015-12-25
+ 5    C     2015-01-01", head=TRUE)
> df1[ order(df1$Name, df1$Date) , ]
  Name       Date
1    A 2015-01-01
4    A 2015-12-25
3    B 2015-01-05
2    B 2016-05-01
5    C 2015-01-01

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM