1
也許我在過度工程這個,但我建立一個功能,根據列輸入數自動解析日期列。解析日期時間適用,返回數字而不是日期對象
數據:
CreatedDate LastModifiedDate
2015-11-20T19:46:11.000Z 2015-11-20T19:46:11.000Z
2015-11-21T02:54:54.000Z 2015-12-01T18:48:07.000Z
2015-11-21T14:36:32.000Z 2015-11-21T14:36:32.000Z
2015-11-21T16:03:41.000Z 2015-11-21T16:03:41.000Z
2015-11-21T17:31:43.000Z 2015-11-21T17:55:13.000Z
require(lubridate)
require(magrittr
parse_sf_hms <- function(subset) {
if(is.null(ncol(subset))){
subset %>% ymd_hms(tz="America/New_York",quiet=TRUE) %>% as.Date(format="%m/%d/%Y") -> x
return(x)
} else {
apply(subset, 2, function(x) x %>% ymd_hms(tz="America/New_York",quiet=TRUE) %>% as.Date(format="%m/%d/%Y"))
return(x)
}
}
所以,問題是,當我使用一列(如df[,1]
或df[,c(CreatedDate)
]),函數正確返回:
[1] "2015-11-20" "2015-11-21" "2015-11-21" "2015-11-21"
[5] "2015-11-21"
但是,當我使用超過一列(例如,df[,c(1,2)]
或df[,c('CreatedDate','LastModifiedDate')]
,而是我得到:
CreatedDate LastModifiedDate
[1,] 16759 16759
[2,] 16760 16770
[3,] 16760 16760
[4,] 16760 16760
[5,] 16760 16760
爲什麼單個向量在格式中正確地返回日期值,而apply卻沒有?在這裏lapply
,rbind
會更好嗎? 只是試圖瞭解行爲。
不要使用'申請(子集2,FUN)'因爲它使一切都是一個矩陣,它將你的日期強制轉換回數字。改用'lapply(subset,FUN)'。 – thelatemail
感謝@thelatemail - 這回答了我關於行爲問題最重要的部分。 – gscott