[R] Creating histograms from factors using a for loop
Peter Ehlers
ehlers at ucalgary.ca
Sat Sep 19 16:07:50 CEST 2009
Sam,
Your loop produces two jpegs but the second overwrites the first.
What do you expect
levels(df[i,"f"])
to produce? (Think about it.)
Try
jpeg(filename=paste(i,".jpg",sep=""))
and you may want to fix the titles as well.
Peter
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()
> }
>
> # I'm obviously not understanding how loops work with factors. Can
> anybody point me in the right direction?
>
More information about the R-help
mailing list