R 我想把因子转换成日期,因子是这样的:2011-05-05:16:30:04.466

R 我想把因子转换成日期,因子是这样的:2011-05-05:16:30:04.466,r,R,我尝试使用润滑包和as.Date(),但都显示错误: # the factor > x [1] '2011-05-05:16:30:04.466 ' 873 Levels: '2011-05-05:16:30:04.466 ' ... '2017-08-10:20:05:51.406967' # try 1 > as.Date(x, format = "%m/%d/%Y") [1] NA # try 2 > xx <- mdy(x) Warning messa

我尝试使用润滑包和
as.Date()
,但都显示错误:

# the factor
> x
[1] '2011-05-05:16:30:04.466   '
873 Levels: '2011-05-05:16:30:04.466   ' ... '2017-08-10:20:05:51.406967'

# try 1
> as.Date(x, format = "%m/%d/%Y")
[1] NA

# try 2
> xx <- mdy(x)
Warning message:
All formats failed to parse. No formats found. 

> xx
[1] NA

> xx <- mdy_hms(x)
Warning message:
All formats failed to parse. No formats found. 
#因素
>x
[1] '2011-05-05:16:30:04.466   '
873级:“2011-05-05:16:30:04.466”2017-08-10:20:05:51.406967'
#试试1
>截止日期(x,格式=“%m/%d/%Y”)
[1] NA
#试试2
>xx xx
[1] NA

>xx看起来您的问题可能是格式。as.Date中的默认格式是“%Y-%m-%d”,这似乎符合示例的要求

> as.Date(as.factor('2011-05-05:16:30:04.466   '), format = "%m/%d/%Y")
[1] NA
> as.Date(as.factor('2011-05-05:16:30:04.466   '))
[1] "2011-05-05"
> as.Date(as.factor('2011-05-05:16:30:04.466   '), format = "%Y-%m-%d")
[1] "2011-05-05"

为了补充Jason Clark的另一个答案,如果你想保持时间,还有
as.POSIXct

getOption("digits.secs")
#NULL

options(digits.secs = 6)

x <- factor('2011-05-05:16:30:04.466')
y <- as.POSIXct(x, format = "%Y-%m-%d:%H:%M:%OS")
y
#[1] "2011-05-05 16:30:04.466 BST"

class(y)
#[1] "POSIXct" "POSIXt"
getOption(“digits.secs”)
#空的
选项(digits.secs=6)
x使用
anytime::anytime()
(用于
POSIXct
)或
anytime::anydate()
(用于
Date
),因为它们将首先为您从
factor
转换为
character
。另外
lubridate::ymd\u hms(factor(“2011-05-05-05:16:30:04.466”)