# 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: spla...@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@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.

Reply via email to