Home » How to Fix: character string is not in a standard unambiguous format

How to Fix: character string is not in a standard unambiguous format

by Erma Khan

One common error you may encounter in R is:

Error in as.POSIXlt.character(x, tz, ...) : 
  character string is not in a standard unambiguous format

This error usually occurs when you attempt to convert an object in R to a date format, but the object is currently either a character or factor.

To fix this error, you must first convert the object to numeric. 

This tutorial explains how to fix this error in practice.

How to Reproduce the Error

Suppose we have the following data frame in R:

#create data frame
df 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

Now suppose we attempt to convert the values in the date column to a date format:

#attempt to convert values in date column to date
df$date POSIXct(df$date, origin='1970-01-01')

Error in as.POSIXlt.character(x, tz, ...) : 
  character string is not in a standard unambiguous format

We receive an error because the values in the date column are currently in a character format, which the as.POSIXct() function doesn’t know how to handle.

How to Fix the Error

To fix this error, we need to use as.numeric() to first convert the values in the date column to a numeric format, which is one that as.POSIXct can handle:

#convert values in date column to date
df$date 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

This time we don’t receive an error and we’re able to successfully convert the values in the date column to a date format because we first converted the values to a numeric format.

Additional Resources

The following tutorials explain how to fix other common errors in R:

How to Fix: (list) object cannot be coerced to type ‘double’
How to Fix in R: invalid model formula in ExtractVars
How to Fix in R: replacement has length zero

Related Posts