你在R中可能遇到的一个常见错误是:
Error in as.POSIXlt.character(x, tz, ...) :
character string is not in a standard unambiguous format
这个错误通常发生在你试图将R中的一个对象转换为日期格式,但该对象目前是一个字符或因子。
要解决这个错误,你必须先将对象转换为数字。
本教程解释了如何在实践中修复这个错误。
如何重现该错误
假设我们在R中拥有以下数据框:
#create data frame
df <- data.frame(date=c('1459397140', '1464397220', '1513467142'),
sales=c(140, 199, 243))
#view data frame
df
date sales
1 1459397140 140
2 1464397220 199
3 1513467142 243
现在假设我们试图将日期列中的值转换为日期格式:
#attempt to convert values in date column to date
df$date <- as.POSIXct(df$date, origin='1970-01-01')
Error in as.POSIXlt.character(x, tz, ...) :
character string is not in a standard unambiguous format
我们收到一个错误,因为日期列中的值目前是字符格式,而**as.POSIXct()**函数不知道如何处理。
如何修复这个错误
为了解决这个错误,我们需要使用 as.numeric()首先将日期列中的值转换成数字格式,这是as.POSIXct可以处理的格式:
#convert values in date column to date
df$date <- as.POSIXct(as.numeric(as.character(df$date)), origin='1970-01-01')
#view updated data frame
df
date sales
1 2016-03-31 04:05:40 140
2 2016-05-28 01:00:20 199
3 2017-12-16 23:32:22 243
这次我们没有收到错误,我们能够成功地将日期列中的值转换为日期格式,因为我们首先将这些值转换为数字格式。
其他资源
下面的教程解释了如何修复R中的其他常见错误:
如何修复:(列表)对象不能被胁迫为'double'类型
如何在R中修复:ExtractVars中的无效模型公式
如何在R中修复:替换的长度为零