What is the as.POSIXct() function in R?
Overview
The as.POSIXct() function in R is used to convert the character type setting default for UTC and 1970 to a POSIXct object.
Syntax
as.POSIXct(x)
Parameter value
The as.POSIXct() function takes the parameter value, x, which represents the character type for UTC.
Return value
The as.POSIXct() function returns a POSIXct object class.
Code example 1
In the example given below, we will create an exemplifying date and time object in R. The class of this object will be checked for using the class() function:
# creating a date and time objectmydate <- "2022-01-30 07:32:59"# printing the date and time objectmydate# checking the class objectclass(mydate)
Code explanation
- Line 2: We create a variable called
mydate, which contains exemplifying data and time characters (30th of January 2022 and 07 hours, 32 minutes, and 59 seconds). - Line 5: We print the variable called
mydate. - Line 8: We obtain the class object of the variable
x, using theclass()function.
Note: It is worth noting that from the output of the code given above,
"character"was returned by theclass()function. Therefore, to convert this character to thePOSIXltclass, we will simply make use of theas.POSIXct()function.
Code example 2
# creating a date and time objectmydate <- "2022-01-30 07:32:59"# implementing the as.POSIXct() functionmydate_POSIX = as.POSIXct(mydate)# printing the POSIXit objectmydate_POSIX# checking the class objectclass(mydate_POSIX)
Code explanation
- Line 5: We implement the
as.POSIXct()function on the variable calledmydate. We assign the result to a variable calledmydate_POSIX. - Line 8: We print the variable called
mydate_POSIX. - Line 11: We also check for the class of the object of the variable
mydate_POSIX, using theclass()function.
Note: When the class function returns a
POSIXctobject, then this means that we successfully converted the character type ofUTCto aPOSIXctobject.