2016-12-01 60 views
-1

我有這樣的數據列表:如何用數據子集數據?

 name     Date 
MANHATTAN STRIKER (V141) 30/11/2016 
MANHATTAN STRIKER (V141) 16/11/2016 
MANHATTAN STRIKER (V141) 26/10/2016 
MANHATTAN STRIKER (V141) 28/9/2016 
YOURTHEWONFORME  (T258) 30/11/2016 
YOURTHEWONFORME  (T258) 9/11/2016 
YOURTHEWONFORME  (T258) 26/10/2016 
FOREVER FUN   (S130) 30/11/2016 
FOREVER FUN   (S130) 16/11/2016 
FOREVER FUN   (S130) 26/10/2016 
FOREVER FUN   (S130) 12/10/2016 

如何我寫R中的腳本只是列出每個名字,在每個日期最新的兩個日期? 造成這樣的:

  name     Date 
    MANHATTAN STRIKER (V141) 30/11/2016 
    MANHATTAN STRIKER (V141) 16/11/2016 
    YOURTHEWONFORME  (T258) 30/11/2016 
    YOURTHEWONFORME  (T258) 9/11/2016 
    FOREVER FUN   (S130) 30/11/2016 
    FOREVER FUN   (S130) 16/11/2016 
+1

嘗試'庫(dplyr); df1%>%group_by(name)%>%arrange(desc(as.Date(Date,「%d /%m /%Y」)))%>%slice(1:2)' – akrun

+0

'dplyr :: top_n (Date,asDate(Date,'%d /%m /%Y'))%>%group_by(name)%>%top_n(2,Date)''方便:'df% – alistaire

回答

-1

我們可以使用dplyr。通過「名稱」分組後,「日期」轉換爲Date類,arrange降序排列,並slice前兩排

library(dplyr) 
df1 %>% 
    group_by(name) %>% 
    arrange(desc(as.Date(Date, "%d/%m/%Y"))) %>% 
    slice(1:2)