2013-05-26 20 views
1

我想比較像兩個「日期字符串」列:處理data.frame以「日期」一欄,其中包括NULL值

df$inpatient.death = (df$date.of.death==df$date.of.discharge)

但是:NULL值的出現似乎阻止我從格式as.Date,以及使用as.character(..)== as.character(..)的不同格式。 什麼是創造

            THIS IS THE AIM: 
    id   date.of.death date.of.discharge [ inpatient.death ] 
1 1 2012-01-01 00:00:00.000  2012-01-01 [   TRUE ] 
2 2     NULL  2012-01-01 [   FALSE ] 
3 3 2012-01-02 00:00:00.000  2012-01-01 [   FALSE ] 

df <- data.frame(id=1:3, date.of.death=c("2012-01-01 00:00:00.000", "NULL", "2012-01-02 00:00:00.000"), date.of.discharge=c("2012-01-01", "2012-01-01", "2012-01-01")) 

什麼是這樣做的最佳方式的最佳途徑?

+0

NULL值從哪裏來?在R中,NA用於缺失值,你的data.frame不應該包含任何NULL值。這意味着你做一些不尋常的事情來創建數據框架,並且應該嘗試去糾正它。另一種可能性是使用'df $ date.of.death [is.null(df $ date.of.death)] < - NA'。 – Roland

+1

請注意,您的示例df只包含一個不是「NULL」值的字符「NULL」。如果你有這些,你應該使用'read.table'的'na.strings'參數或者你用來讀取文件的函數。 – Roland

+0

@Roland:「NULL」來自csv導入,但我後來設法使用as.Date轉換爲as.Date(df $ date.of.death,「%Y-%m-%d 00:00: 00.000" ) – ajo

回答

1
df <- data.frame(id=1:3, date.of.death=c("2012-01-01 00:00:00.000", "NULL", "2012-01-02 00:00:00.000"), 
       date.of.discharge=c("2012-01-01", "2012-01-01", "2012-01-01")) 

df$inpatient.death <- as.Date(df$date.of.death)==as.Date(df$date.of.discharge) # date.of.death is already in the standard format no need to specify 
df$inpatient.death[is.na(df$inpatient.death)] <- F 

> df 
    id   date.of.death date.of.discharge inpatient.death 
1 1 2012-01-01 00:00:00.000  2012-01-01   TRUE 
2 2     NULL  2012-01-01   FALSE 
3 3 2012-01-02 00:00:00.000  2012-01-01   FALSE 

# you can also definy an helper function for this task 

`==2` <- function(x,y){ 
    res <- x==y 
    res[is.na(res)] <- F 
    res 
} 

df$inpatient.death <- `==2`(as.Date(df$date.of.death),as.Date(df$date.of.discharge)) 

> df 
    id   date.of.death date.of.discharge inpatient.death 
1 1 2012-01-01 00:00:00.000  2012-01-01   TRUE 
2 2     NULL  2012-01-01   FALSE 
3 3 2012-01-02 00:00:00.000  2012-01-01   FALSE