[R] make changes in existing vector with the apply function?
William Dunlap
wdunlap at tibco.com
Mon Sep 27 18:08:50 CEST 2010
> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Jonas Sundberg
> Sent: Monday, September 27, 2010 1:43 AM
> To: r-help at r-project.org
> Subject: [R] make changes in existing vector with the apply function?
>
>
> Hi, I'm trying to make some changes in a vector according to
> some conditions. It takes too long time however with vector
> length > 100000 and I guess a better way would be using the
> apply function. I cannot sort out how, however.
> As a for/if loop:
> for (i in 1:length(PrH)) {
> if (is.finite(PrH[i]) == F & tempHER > tempSPR) {PrH[i] <- 1 }
> if (is.finite(PrH[i]) == F & tempHER < tempSPR) {PrH[i] <- 0 }}
> PrH, tempSPR and tempHER are equally long vectors.
Did that code ever work? I would have thought that
your tempHER and tempSPR would require a [i] after them.
(Otherwise you would get warnings and incorrect results.)
If so, a first step is to replace your for loop with
PrH[!is.finite(PrH) & tempHER>tempSPR] <- 1
PrH[!is.finite(PrH) & tempHER<tempSPR] <- 0
Read the '[' as 'such that' when using logical-valued
subscripts.
If time or memory is at a premium you may get slightly
better mileage from more complicated code. E.g.,
in the following we compute is.inite(PrH) only once
and use the fact that as.integer maps TRUE and FALSE
to 1 and 0, respectively:
PrHIsInfinite <- !is.finite(PrH)
PrH[PrHIsInfinite] <- as.integer(tempHER[PrHIsInfinite]>tempSPR[PrHIsInfinite])
I haven't tested any of this.
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> Thanks in advance!Jonas
>
>
>
> [[alternative HTML version deleted]]
>
>
More information about the R-help
mailing list