[R] Creating histograms from factors using a for loop

Sam Player samtplayer at gmail.com
Sat Sep 19 11:37:36 CEST 2009


# 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?

-- 
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




More information about the R-help mailing list