[R] troubles with a for loop

Sarah Goslee sarah.goslee at gmail.com
Sun Sep 18 18:31:21 CEST 2011


You don't have a variable named pd.memb.i

Instead, you need something like:
get(paste("pd.memb.", i, sep=""))

The error message you're getting, though, is because your
loop syntax is wrong:
for(i in 1:3) {
 do something
}

Sarah

On Sun, Sep 18, 2011 at 12:05 PM, Francesco Sarracino
<f.sarracino at gmail.com> wrote:
> Dear all,
>
> I am a stata user and I am moving my first steps in R.
> I am dealing with a silly issue concerning looping over variables. I read
> previous posts on similar topics in the R help archive, but I did not find a
> solution.
> Here is my case:
>
> I run a simple bivariate linear regression saving the output in objects
> called: pd.memb.0, pd.memb.1, pd.memb.2, pd.memb.3
>
> pd.memb.0 <- lm(E.fs.memb ~ M.fs.memb, data, subset = (tag2 == 1))
> pd.memb.1 <- lm(E.fs.memb ~ M.fs.memb, data, subset = (M.fs.memb <=
> quantile(M.fs.memb, .25) & tag2 == 1))
> pd.memb.2 <- lm(E.fs.memb ~ M.fs.memb, data, subset = (M.fs.memb >
> quantile(M.fs.memb, .25) & M.fs.memb <= quantile(M.fs.memb, .75) & tag2 ==
> 1))
> pd.memb.3 <- lm(E.fs.memb ~ M.fs.memb, data, subset = (M.fs.memb >
> quantile(M.fs.memb, .75) & tag2 == 1))
>
> Subsequently, I wish to plot my data superimposing a different line for each
> regression model. Here I am trying to apply my loop. Looking at the info I
> found around, the following code sound to me as correct, but I am wrong.
>
> plot(M.fs.memb , E.fs.memb)
> for(i =  1:3){
>  curve(coef(pd.memb.i)[1] + coef(pd.memb.i)[2]*x, add = T, cex = 100, col =
> "red")
> }
>
> The plot is plotted, but the curves are not printed and  I get the following
> error message:
>
>
> Error in coef(pd.memb.i) :
>  error in evaluating the argument 'object' in selecting a method for
> function 'coef'> }Error: unexpected '}' in "}"
>
>
> What am I doing wrong?
> Thanks a lot for your help,
> f.
>
>        [[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.
>



-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list