2016-04-23 45 views
0

我想用for loop生成ggplots的列表。用于ggplot2中的循环生成列表

sig_snp<-c("rs644045_A","rs12997044_C","rs17739727_A") 

p_re<-list() 

for (i in sig_snp){ 
test %>% dplyr::select(i,type,micro1) %>% 
ggplot(aes(factor(type),log(micor1))) + 
geom_boxplot(aes(fill = factor(i)))+ 
xlab('')+ylab('log abundance')->p_re[[i]] 
} 

的埃罗如下所示:

Error: All select() inputs must resolve to integer column positions. The following do not: * i

我已经以这种方式测试了每个i for循环:

test %>% dplyr::select(rs644045_A,type,micro1) %>% 
    ggplot(aes(factor(type),log(micor1))) + 
    geom_boxplot(aes(fill = factor(rs644045_A)))+ 
    xlab('')+ylab('log abundance') 

它的工作单,但为什么在循环无法正常工作?

+0

'test'在哪里?请显示一个可重复的例子 – akrun

+1

[关于如何给出一个可重复的例子的信息](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610) – Jaap

+0

我认为这是一个语法问题:如何使for循环中的'i'被识别为没有引号的原始名称?当我在for循环中测试每个'i'时,它会单独工作。 – Ming

回答

0

如果你需要保持每SNP ggplot输出列表中,它也许是更好使用lapply将输出列表,例如:

library(ggplot2) 

#dummy data 
test <- mtcars 

#significant SNPs 
sig_snp <- c("mpg", "cyl", "disp") 

#create list of ggplots per SNP 
p_re <- 
    lapply(sig_snp, function(i){ 

    ggplot(test, aes_string("qsec", i)) + 
     geom_point() 

    }) 

#assign names 
names(p_re) <- sig_snp 

#plot 
p_re$mpg 
1

棘手的部分是select_get()

get()答案是从这里开始:Remove quotes from a character vector in R

然而,在我的情况下,它没有在工作loop.I认为这可能是由于增加一倍在我的代码循环(我不知道)。

无论如何,有是让它的另一种方式:

test[,c(sig_snp,"type","micro1")]%>% 
    melt(id=c("type","micro1"))%>% # head() 
    ggplot(aes(factor(type),log(micro1))) + 
    geom_boxplot(aes(fill = factor(value)))+ 
    xlab('')+ylab('log abundance')+facet_grid(.~variable) 

我的想法从这里Looping over variables in ggplot