[R] Creating histograms from factors using a for loop

David Winsemius dwinsemius at comcast.net
Sat Sep 19 16:19:45 CEST 2009


On Sep 19, 2009, at 5:37 AM, Sam Player wrote:

> # I have a dataframe with data and factors similar to the following:
>
> a <- rep(c("a", "b"), c(6,6))
> df <- data.frame(f=a, d=rnorm(12))
> df
>
> # I am trying to write a 'for' loop which will produce a jpeg  
> histogram for each factor. I can individually isolate the data from  
> a factor and produce a jpeg histogram like so:
>
> fnc <- function(x){
>        x <- df[df$f=="a", "d"]
> }
>
> y <- fnc(df[df$f=="a", "d"])
>
> jpeg(filename="foo.jpeg")
> hist(y)
> dev.off()
>
> # I'm having trouble creating a loop repeating the process for all  
> the other factors. The following is the best I could come up with.  
> It produces a single jpeg histogram of the first factor titled with  
> a list of all the factors.
>
> a <- rep(c("a", "b"), c(6,6))
> df <- data.frame(f=a, d=rnorm(12))
> df
>
> for (i in levels(df[,"f"])){
>        y <- df[df$f==i, 2]
>        jpeg(filename=(levels(df[i,"f"])))
>        hist(y, main=levels(df[i,"f"]))
>        dev.off()
>        }

You are a bit unclear about what you are seeking but if you want  
separate file names and titles that are factor-specifich, then why not  
use "i" inside the loop as itself?

for (i in levels(df[,"f"])){
        y <- df[df$f==i, 2]
        jpeg(filename=paste("file_",i,sep=""))
        hist(y, main=paste("Factor =",i,sep=""))
        dev.off()
        }
>
> # I'm obviously not understanding how loops work with factors.

It seems that you are unclear about loop indices. You are not really  
passing factors anyway, but rather elements of a character vector,  
levels(df[,"f"]).

> Can anybody point me in the right direction?
>
> -- 
> Sam Player, B.Sc.(Hons.) B.A.
> Ph.D. Candidate, Faculty of Agriculture, Food & Natural Resources,  
> University of Sydney
>
> Email: splayer at usyd.edu.au
>
> Agroecosystems Research Group
> Room 214 J.R.A. McMillan Building A05
> University of Sydney NSW 2006, Australia
>
> Angkor Research Program
> Room 305 Old Teachers College A22
> University of Sydney NSW 2006, Australia
>
> ______________________________________________
> 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.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list