在R中转换日期

时间:2015-09-01 18:31:55

标签: r date

我在CSV文件中的数据集中的日期格式为yyyy/mm/dd。输入到R时,它们是因子,格式为"01-Aug-12"

我尝试了以下内容:

as.Date(x=df$Date.of.Visit, format="%d %b %Y") 

我得到的全部是NA。这可能是因为R看到的年份不是4位数? ('12而不是2012)。

2 个答案:

答案 0 :(得分:0)

在as.Date的R文档中:

## read in date info in format 'ddmmmyyyy'
## This will give NA(s) in some locales; setting the C locale
## as in the commented lines will overcome this on most systems.
## lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C")
x <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
z <- as.Date(x, "%d%b%Y")
## Sys.setlocale("LC_TIME", lct)
z

在您的情况下,只需:

lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C")
as.Date(x=df$Date.of.Visit, format="%d-%b-%y") 
Sys.setlocale("LC_TIME", lct)

答案 1 :(得分:0)

或者,使用lubridate:

library(lubridate)
df$realdate <- ymd(df$Date.of.Visit)

然后格式不重要。

相关问题