You know how you can supply a vector of names to a data frame to change the col or row names of a dataframe. Is there a similar method to supply a vector of names that alte
Try this:
toCls <- function(x, cls) do.call(paste("as", cls, sep = "."), list(x))
replace(DF,, Map(toCls, DF, cls))
Second example. Also try this example (which allows NA
to be used for any column whose class is not to be changed). We load the zoo package since it provides a version of as.Date
that has a default origin and we define our own as.POSIXct2
to likewise avoid having to otherwise specify the origin.
library(zoo) # supplies alternate as.Date with a default origin
as.NA <- identity
as.POSIXct2 <- function(x) as.POSIXct(x, origin = "1970-01-01")
cls2 <- c("character", "Date", NA, "factor", "POSIXct2")
replace(DF,, Map(toCls, DF, cls2))
Note that its only when converting numbers to "Date"
or "POSIXct"
that there are origin considerations and when converting character strings such as "2000-01-01"
no origin would need to be specified in any case so for such situations we would not need to load zoo and we would not need our own version of as.POSIXct
.
EDIT: Added another example.