[R] simple usage of "for"

Duncan Murdoch murdoch at stats.uwo.ca
Tue Feb 19 16:04:13 CET 2008


On 2/19/2008 9:24 AM, Hans Ekbrand wrote:
> Hi list
> 
> I have a data frame I would like to loop over. To begin with I would
> like crosstabulations using the first variabel in the data frame,
> which is called "meriter".
> 
>> table(meriter[[1]], meriter[[3]])
>                                                       
>                                                           ja nej
>   Annan                                                 0  2   1
>   Avdelningen för teknik- och vetenskapsstudier         0  5   1
>   CEFOS                                                 0  6   3
>   Förvaltningshögskolan                                 0 13   6
>   Institutionen för globala studier                     0 20  12
>   Institutionen för journalistik och masskommunikation  0  5  17
>   Institutionen för socialt arbete                      1 19  35
>   Psykologiska institutionen                            0 24  21
>   Sociologiska institutionen                            0 16  12
>   Statsvetenskapliga institutionen                      0 19  12
>>
> 
> I tried the following small code snippet which I copied from the
> "Introduction to R":
> 
>> for (i in 2:length(meriter)) { table(meriter[[1]], meriter[[i]]) }

Where did you find that?  I don't see anything like it.  (If there is 
something like that, it should be fixed.)

If you are referring to this snippet:

 >for (i in 1:length(yc)){
     plot(xc [[i ]],yc [[i ]]);
     abline(lsfit(xc [[i ]],yc [[i ]]))
}

then it has the important difference that plot() and abline() both have 
side effects (they do plotting), whereas table() doesn't.

Duncan Murdoch

> 
> And there is no output at all, just a new prompt.
> 
> I added a print statement just to check the loop construct, and it
> seems to work.
> 
>> for (i in 2:length(meriter)) { print(i); table(meriter[[1]], meriter[[i]]) }
> [1] 2
> [1] 3
> [1] 4
> 
> But I get no tables :-(
> 
> What do I do wrong?
> 
> 
> 
> ------------------------------------------------------------------------
> 
> ______________________________________________
> 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