[R] For and if confusion
Gabor Grothendieck
ggrothendieck at gmail.com
Thu Dec 18 16:57:21 CET 2008
Here is a solution that only uses ts (no zoo) starting from
the dates:
fmt <- "%d-%m-%Y"
X <- as.Date(c("01-03-1993", "01-05-1997"), fmt)
Y <- as.Date(c("01-02-1995", "01-08-1999"), fmt)
ym <- function(x) with(as.POSIXlt(x), c(1900 + year, mon+1))
Xt <- ts(1, start = ym(X[1]), end = ym(X[2]), freq = 12)
Xt <- ts(1, start = ym(Y[1]), end = ym(Y[2]), freq = 12)
Xt2 <- cbind(Xt, A)[, 1]
Yt2 <- cbind(Yt, A)[, 1]
Xt2[is.na(Xt2)] <- 0
Yt2[is.na(Yt2)] <- 0
pmax(Xt2, Yt2)
On Thu, Dec 18, 2008 at 10:05 AM, Gabor Grothendieck
<ggrothendieck at gmail.com> wrote:
> Make a series of ones from each start/end pair and merge them all
> with A using fill = 0. We have returned a ts series since that seems
> to be what you are using but we could have left off the as.ts to
> return a zoo series in the end:
>
> library(zoo)
>
> X <- as.Date(c("01-03-1993", "01-05-1997"), "%d-%m-%Y")
> Xs <- zoo(1, as.yearmon(seq(X[1], X[2], "month")))
>
> Y <- as.Date(c("01-02-1995", "01-08-1999"), "%d-%m-%Y")
> Ys <- zoo(1, as.yearmon(seq(Y[1], Y[2], "month")))
>
> A <- ts(rnorm(120), freq=12, start=c(1992,8))
> as.ts(with(merge.zoo(Xs, Ys, A, fill = 0), pmax(Xs, Ys)))
>
>
>
> On Thu, Dec 18, 2008 at 5:12 AM, Shruthi Jayaram
> <shruthi.jayaram.85 at gmail.com> wrote:
>>
>> I have two date objects
>>
>> X <- c("01-03-1993", "01-05-1997") #Mar 1993 and May 1997
>>
>> Y <- c("01-02-1995", "01-08-1999") #Feb 1995 and Aug 1999
>>
>> and a time series object
>>
>> A <- ts(rnorm(120), freq=12, start=c(1992,8)) #Aug 1992 to Aug 2002
>>
>> I want to create a binary (0-1) vector B that is of length 1:(A).
>>
>> B should have value 1 for the time periods *across* my character vectors,
>> i.e. between Mar 93 ad Feb 95, and also between May-97 and Aug-99, but zero
>> otherwise.
>>
>> Would anyone have any ideas on how to do this? I would paste the code I am
>> trying, but it would confuse rather than clarify (R newbie!). Am getting
>> really lost in 'for' and 'if' loops, so would really appreciate any help!
>>
>> Thanks!
>>
>> Shruthi
>> --
>> View this message in context: http://www.nabble.com/For-and-if-confusion-tp21069934p21069934.html
>> Sent from the R help mailing list archive at Nabble.com.
>>
>> ______________________________________________
>> R-help at r-project.org 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.
>>
>
More information about the R-help
mailing list