我有一个包含许多可能的变量组合的数据框,出于探索目的,我需要从这些变量组合中看到单变量分布。我成功地使用for循环,但希望找到一种更好,更快的方法。有人有想法吗?
我制作了以下代码:
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)
}
}
如何在此图形打印中替换嵌套的for循环?
答案 0 :(得分:0)
您可以尝试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]))