[R] Trying to avoid loop structure

Phil Spector spector at stat.berkeley.edu
Wed Sep 29 21:13:23 CEST 2010


Mathieu -
    First of all, you can combine as many conditions as 
you want in an if statement, using && (and) and || (or).
So to say
     coef$st[i-1] < obs[t] < coef$st[i]
use
     coef$st[i-1] < obs[t] && obs[t] < coef$st[i]

So following your logic, you could use

x = numeric(length(obs))
for(t in 1:length(obs)) {
       for(i in 1:length(coef$st))
          if(coef$st[i-1] < obs[t] && obs[t] < coef$st[i])
            x[t] = coef$b[i] + (coef$a[i] * obs[t])
     }

Alternatively, you could solve the problem using R:

mapply(function(o,i)coef$b[i] + coef$a[i] * o, obs,
                     cut(obs,c(coef$st,6),labels=FALSE) + 1)

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu





On Wed, 29 Sep 2010, Mathieu Beaulieu wrote:

>
> Dear R-helpers,
> I'm trying to associate linear coefficients (intercept and slope) to tens of thousands of observations based on a table with benchmark values.
> #####Example - Value table and their corresponding coefficients (intercept and slope)
> coef = data.frame(cbind(st=c(1:5),b = runif(5,0.3,5),a = seq(0.5,5,1)))print(coef)
> #Example of observations to be computedobs = runif(20,1,5)print(obs)
>
> #This should be fairly simple - but I can't get the loop structure out of my head. I don't know how to tell the software "if the observation is greater than st[i-1] but smaller than st[i], use a[i] and b[i] - otherwise go to the next line".So far, I've tried this:
> for(t in 1:length(obs)) {
> 	for(i in 1:length(coef$st)) if(coef$st[i-1] < obs[t] < coef$st[i]) x[t] = coef$b[i] + (coef.$a[i] * obs[t])
> 	}#####
> Doesn't work - if statement do not accept double conditions structure (y[-1] < x < y) and I should put an else statement - but i'm stuck there. I have the feeling I should look into lapply but it doesn't seem like lapply works with "if" statements.
> Any tips would be much appreciated,
> Thanks,
>
>
> Mathieu Beaulieu,
> Soil, Water & Environment Laboratory
> Institute for Resources, Environment and Sustainability
> University of British-Columbia
> 429-2202 Main Mall,
> Vancouver, BC,
> V6T 1Z4
> Canada
>
>
>
>
>
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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