# [R] troubles with a for loop

Patrick Burns pburns at pburns.seanet.com
Sun Sep 18 19:23:43 CEST 2011

Sarah has told you how to get from where
you are to where you want to be.

However, it is easier to start somewhere
else.  The more "R" way to do what you are
doing is to use a list to put the results
of your regressions into.  It is then very
easy to use that list, and it is easier to
keep track of.

The two documents mentioned in my signature
may help you get up and running in R.  Since
you are coming from Stata, you should also
look at http://r4stats.com

On 18/09/2011 17:05, Francesco Sarracino 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.
>

--
Patrick Burns
pburns at pburns.seanet.com