2012-10-04 15 views
2

我有一個數據框,其中一列是(意味着)在00:00:00.0 yyyy-mm-dd形式的日期。大部分條目都是,但有些則不是。有沒有辦法刪除包含非日期的行?類似於(如果列是「日期」)R刪除行的條目不是日期

data <- data[is.Date(DATE)==TRUE,] 

例如,

Fruit Date 
apple 00:00:00.0 2005-02-01 
pear 00:00:00.0 2006-02-01 
orange 00:00:00.0 -8-2-402145 
rhino 00:00:00.0 2003-04-21 

我想

Fruit Date 
apple 00:00:00.0 2005-02-01 
pear 00:00:00.0 2006-02-01 
rhino 00:00:00.0 2003-04-21 
+3

你能使用它們轉換爲日期,時間格式'strptime'和那麼任何「不是」的時間最終都會成爲「NA」,因此輕鬆刪除。 – joran

回答

2

繼joran的推理:

# get the test data 
test <- data.frame(
    Fruit=c("apple","pear","orange","rhino"), 
    Date=c("00:00:00.0 2005-02-01", 
      "00:00:00.0 2006-02-01", 
      "00:00:00.0 -8-2-402145", 
      "00:00:00.0 2003-04-21") 
) 

# remove the rows by checking if not (!) an NA due to not meeting the date format 
test[!is.na(strptime(test$Date,format="00:00:00.0 %Y-%m-%d")),] 

結果:

Fruit     Date 
1 apple 00:00:00.0 2005-02-01 
2 pear 00:00:00.0 2006-02-01 
4 rhino 00:00:00.0 2003-04-21