[R] for loop

David Winsemius dwinsemius at comcast.net
Sat Oct 30 21:10:33 CEST 2010


On Oct 30, 2010, at 3:00 PM, Matevž Pavlič wrote:

> Just one more thing...
> I get a list with 15 data.frames :
>
> List of 15
> $ 1:'data.frame':      7 obs. of  9 variables:
>  ..$ vrtina         : Factor w/ 6 levels "T1A-1","T1A-2",..: 1 1 2 2  
> 5 5 5
>  ..$ globina.meritve: num [1:7] 7.6 8.5 10.4 17.4 12.5 15.5 16.5
>  ..$ E0             : num [1:7] 4109 2533 491 810 2374 ...
>  ..$ Eur1           : num [1:7] 6194 4713 605 1473 NA ...
>  ..$ Eur2           : num [1:7] 3665 7216 266 4794 7387 ...
>  ..$ Eur3           : num [1:7] 3221 3545 920 3347 6768 ...
>  ..$ H              : num [1:7] 8 5.9 5.9 6.9 9.3 10.9 10
>  ..$ Mpl            : num [1:7] 61.9 136.7 19.9 96.4 178.5 ...
>  ..$ class          : int [1:7] 1 1 1 1 1 1 1
> .
> But how would I acces them (i.e. to draw a plot for each data.frame  
> for each data.frame in a list)?

Something along the lines of one of these:

lapply(dfrm.list, function(xfrm) with(xfrm, plot(Mpl, E0) ) )

lapply(dfrm.list, function(xfrm) plot(E0 ~ Mpl, data=xfrm) ) )

... assuming you wanted a scatterplot. If you wanted them all on one  
page, then see:

?layout

If you used lattice or ggplot plotting function they do not work via  
side-effects and so you could assign the results creating a list of  
plots.

-- 
DAvid.


>
> Thanks,m
>
> -----Original Message-----
> From: David Winsemius [mailto:dwinsemius at comcast.net]
> Sent: Saturday, October 30, 2010 8:24 PM
> To: Matevž Pavlič
> Cc: r-help at r-project.org
> Subject: Re: [R] for loop
>
>
> On Oct 30, 2010, at 2:07 PM, Matevž Pavlič wrote:
>
>> Hi,
>>
>> I know this is probalby a very trivial thing to do for most of the R
>> users, but since I just strated using it I have some problems....
>>
>> I have a data.frame with a field called "razred". This field has
>> values from 1 up to 15.
>>
>> Is it possible to create a for loop that would create a new data  
>> frame
>> for each of the "razred" values.
>
> The R-way would be to use the split function and leave the result in  
> a list to which the same operation could be also repeatedly  
> performed using lapply.
>
> ?split
>
> And take a look at the fourth example applying split to the builtin  
> airquality dataframe.
>
> The plyr package also provides functions on dataframes.
>
> -- 
>
> David Winsemius, MD
> West Hartford, CT
>

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list