0

I have a dataframe with lots of possible combinations of variables and for exploratory purposes I need to see univariate distributions from these combinations of variables. I succeeded doing it with for loops but would like to find a better and a faster way of doing it. Anybody has an idea?

I have produced a following code:

library(ggplot2)
library(dplyr)
SubjectID <- c(3772113,3772468)
Group <- c("Easy","Hard")
Object <- c("A","B")
dat <- data.frame(expand.grid(SubjectID,Group,Object))
dat$RT <- rnorm(8,1500,700)
colnames(dat) <- c("SubjectID","Group","Object","RT")

# GGplot function
pl <- function(x,group, object){
  x <- filter(x, Group==group, Object==object)
  print(ggplot(x,aes(x=RT)) + 
          geom_histogram(binwidth = 0.05) +
          xlab("Reactions per second") +
          ggtitle(paste(as.character(group),"_",as.character(object)), sep=""))
  ggsave(paste(as.character(group),"_",as.character(object),".png"), path = "...")
}

for (group in unique(dat$Group)){
  for (object in unique(dat$Object)){
    pl(dat,group,object)
  }
}

How can I replace the nested for loops in this graph printing?

3
  • edited your answer with dat instead of sp(otherwise not reproducible). Also, I think your paste line should finish with ,".png", sep="") or paste be turned into paste0 otherwise spaces are added in the filenames. Apr 4, 2016 at 11:44
  • Faceting is not an option?
    – Roland
    Apr 4, 2016 at 11:52
  • @Roland It was an option, but the quality was a bit bad (there are 11 objects in the "real" dataframe). Thanks!
    – User33268
    Apr 4, 2016 at 14:38

1 Answer 1

0

You can try with lapply:

all_comb <- with(dat, expand.grid(levels(Group), levels(Object)))
lapply(1:nrow(all_comb), 
       function(i) pl(dat, group = all_comb[i, 1], object=all_comb[i, 2]))
1
  • Tried and it works! Sadly it's not much quicker than for loops... Thank you!
    – User33268
    Apr 4, 2016 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.