Here are some alternatives. Each changes the date part to 2016-06-01. No packages are used.
1) sub Replace the leading non-spaces with the date and convert back to POSIXct. Note that sub
automatically converts p
to character so we do not need to do that explicitly. No packages are used:
as.POSIXct(sub("\\S+", "2016-06-01", p))
1a) This is a similar alternative. The replacement converts it back to POSIXct:
replace(p, TRUE, sub("\\S+", "2016-06-01", p))
2) arithmetic Another possibility is to subtract off the date and add on the new one. There may be time zone problems if we do not use format
as shown:
p - as.POSIXct(as.Date(format(p))) + as.POSIXct("2016-06-01")
3) POSIXlt list This converts to POSIXlt lists, resets the year, mon and mday components and in the last line converts back.
toList <- function(x) unclass(as.POSIXlt(x))
m <- modifyList(toList(p), toList("2016-06-01")[c("year", "mon", "mday")])
as.POSIXct(structure(m, class = "POSIXlt"))
4) POSIXlt This converts to POSIXlt and sets the components directly:
with(unclass(as.POSIXlt("2016-06-01")), {
p.lt <- as.POSIXlt(p)
p.lt$year <- year
p.lt$mon <- mon
p.lt$mday <- mday
as.POSIXct(p.lt)
})
Note: The input p
used in all the solutions above in reproducible form is:
p <- structure(c(1462083934, 1462083623, 1462083238, 1462083033, 1462082856,
1462082581), class = c("POSIXct", "POSIXt"), tzone = "")
mutate
for instance? – Divulgate