Convert date to character in a data frame

Viewed 6042

I would like to convert date columns (Date, POSIXct, POSIXt) into character columns in a data frame. For example, I have this data frame.

df <- data.frame(date = Sys.Date(), time = Sys.time(), val = 1)

I can easily use the manual way like this to convert date columns into character columns.

df$date <- as.character(df$date)
df$time <- as.character(df$time)

Is there any way that I can convert them in a whole without specifying the date columns one by one? How could I convert them using lapply or sapply function?

1 Answers

First, make a more complete example, with a mix of data types. Then, determine which ones are of class Date or POSIXt. And finally, modify just the ones of interest.

df <- data.frame(date = Sys.Date(), time = Sys.time(), x = 1, A = "Test")

inx <- sapply(df, function(x) inherits(x, "Date") || inherits(x, "POSIXt"))
df[inx] <- lapply(df[inx], as.character)
str(df)
#'data.frame':   1 obs. of  4 variables:
# $ date: chr "2017-11-05"
# $ time: chr "2017-11-05 08:30:19"
# $ x   : num 1
# $ A   : Factor w/ 1 level "Test": 1

Note that other date/time classes such as POSIXct and POSIXlt both inherit from class POSIXt so you only have to test this latter.

Related