On Mon, 30 Apr 2012, Santiago Guallar wrote:

Hello,

I'm having problems working with date values in POSIXct format.

Indeed you are.

Here is what I got (eg.lig attached):

x <- read.table("eg.txt", sep = ',', col.names=c("ok","time","secs","lig")) # 
it gives time as factor
z <- cbind(x,colsplit(x$time, split="\\s", names=c("date", "clock")))

colsplit is not defined in base R, and it is redefined in a couple of packages. I am guessing you mean the one that is in the reshape package.

zh<-cbind(z,colsplit(z$clock,split=":",names=c("h","m","s")))
zn <- subset(zh, zh$lig<= 5 & zh$h<8 | zh$h>=22) # nighttime
zn$timepos<-as.POSIXct(zn$time,tz="GMT",format="%d/%m/%y %H:%M:%S")

I want to assign timepos to its ?natural? night, that is, the night that goes from sunset of day x to sunrise of day x+1 corresponds to day x:

You are working here with GMT, but there are many other possible timezones that this data could correspond to, and if the input time really is in GMT, then the interval of night could be anytime.


zn$night<-ifelse(zn$h>=0 & zn$h<9,zn$timepos ??oneday?,zn$timepos)  #doesn?t 
work

How can I subtract one day (24 hours) to zn$timepos and obtain a POSIXct output?

Well, a literal answer to your question is:

zn$timepos - as.difftime( 1, units="days" )

but in response to your stated goal perhaps you should study the following:

library(maptools)
Sys.setenv( TZ="GMT" ) # set to the local timezone for column "time"
dta <- read.table( "eg.txt"
                 , sep=','
                 , col.names=c("ok","time","secs","lig")
                 , stringsAsFactors=FALSE)
dta$dtm <- as.POSIXct( dta$time, format="%d/%m/%y %T" ) # depends on TZ
# site is invented in GMT timezone for illustration
site <- SpatialPoints( matrix( 0, 51.5, nrow=1 )
                     , proj4string=CRS("+proj=longlat +datum=WGS84" ) )
dta$rise <- sunriset( site
                    , dta$dtm
                    , direction="sunrise"
                    , POSIXct.out=TRUE )$time
dta$set <- sunriset( site
                   , dta$dtm
                   , direction="sunset"
                   , POSIXct.out=TRUE )$time
dta$isnight <- with( dta, !( rise < dtm & dtm < set ) )


---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<[email protected]>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
---------------------------------------------------------------------------
______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to