r - replace only date in PosixCt class -


i have large dataframe of dates in posixct format. objective simple: change of dates 1 day - 2016-05-01 - while keeping of times same. how proceed replace first 10 characters in string (of every row) if convert sample$newtime character?

> class(sample$newtime) [1] "posixct" "posixt"   > head(sample)                       newtime  1 2016-05-01 02:25:34 2 2016-05-01 02:20:23 3 2016-05-01 02:13:58 4 2016-05-01 02:10:33 5 2016-05-01 02:07:36 6 2016-05-01 02:03:01 > dim(sample)      [1] 92020     1 > range(sample$newtime) [1] "2015-01-01 01:04:29 msk" "2016-06-15 12:45:03 msk" 

here alternatives. each changes date part 2016-06-01. no packages used.

1) sub replace leading non-spaces date , convert posixct. note sub automatically converts p character not need explicitly. no packages used:

as.posixct(sub("\\s+", "2016-06-01", p)) 

1a) similar alternative. replacement converts posixct:

replace(p, true, sub("\\s+", "2016-06-01", p)) 

2) arithmetic possibility subtract off date , add on new one. there may time zone problems if not use format shown:

p - as.posixct(as.date(format(p))) + as.posixct("2016-06-01") 

3) posixlt list converts posixlt lists, resets year, mon , mday components , in 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 converts posixlt , sets 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: input p used in solutions above in reproducible form is:

p <- structure(c(1462083934, 1462083623, 1462083238, 1462083033, 1462082856,      1462082581), class = c("posixct", "posixt"), tzone = "") 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -