簡體   English   中英

R日期時間轉換-lapply和unlist轉換為紀元后的幾天

[英]R Date time conversion - lapply and unlist is converting to days after the epoch

我正在為看起來像12/8/12日期轉換字符串,可能以一種相當12/8/12方式通過1)在日期和月份數字中添加前導零(零填充),然后使用as.Date函數轉換為date對象在我編寫的自定義函數中

date_conversion <-  function(date_string){
  split <- unlist(strsplit(date_string, "/"))  
  split[1] = str_pad(split[1], 2, pad = "0")
  split[2] = str_pad(split[1], 2, pad = "0")
  t = as.Date(paste(split, collapse = "/"),format='%m/%d/%y')
  return (t)
}

非常令人困惑的是,當我在一個輸入上調用該函數時,我可以獲得我想得到的結果:

> date_conversion(test[1])
[1] "2012-12-12"
> typeof(date_conversion(test[1]))
[1] "double"

然后,當我使用lapply ,它將返回以下字符串表示形式:

    > lapply(test, date_conversion)
[[1]]
[1] "2012-12-12"

[[2]]
[1] "2015-12-12"

[[3]]
[1] "2015-09-09"

然后,當我調用unlist ,日期將更改為自該紀元以來的天數:

 unlist(lapply(test, date_conversion))
[1] 15686 16781 16687

我猜想日期的基本表示形式是自紀元以來的天數(因此typeof返回雙unlist ,但是為什么列表值會以更易讀的形式顯示日期格式,然后調用unlist使其回到自紀元形式以來的這一天?

此外,我是否可以通過這種優雅的方式進行轉換? 也許我不應該使用Lapply?

lubridate軟件包還有另一種解決方案:

test <- c("12/8/12", "1/1/13", "2/4/13")

dates <- lubridate::mdy(test)
##[1] "2012-12-08" "2013-01-01" "2013-02-04"

class(dates)
##Date[1:3], format: "2012-12-08" "2013-01-01" "2013-02-04"

str(dates)
##[1] "Date"

lubridate函數mdy()將對象test的字符串轉換為月(m),天(d)和年(y)。 如果您的對象test是列表,則可以使用lubridate::mdy((unlist(test))lubridate::mdy((unlist(test))相同的答案。

您不需要date_conversion函數,因為as.Date可以使用日期字符串的格式,並且它是矢量化的。 因此,如果test是您的日期作為字符串的向量:

test <- c("12/8/12", "1/1/13", "2/4/13")
print(result)
result <- as.Date(test, format="%m/%d/%y")
##[1] "2012-12-08" "2013-01-01" "2013-02-04"
str(result)
##Date[1:3], format: "2012-12-08" "2013-01-01" "2013-02-04"
class(result)
##[1] "Date"

如果test是一個list ,然后unlist第一(即, as.Date(unlist(test), format="%m/%d/%y")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM