0

I would like to use for loop to generate a list of ggplots.

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

The erro shows below:

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

I have tested each i in the for loop in this way:

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

It worked singly, but why not work in the loop?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Ming
  • 181
  • 2
  • 10
  • Where is `test`? Please show a reproducible example – akrun Apr 23 '16 at 16:17
  • 1
    [Info on how to give a reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610) – Jaap Apr 23 '16 at 16:18
  • I thought it was a syntax problem: How to make the `i` in the for loop to be recognized as the raw name without quotation marks? As I tested each `i` in the for loop, it worked singly. –  Ming Apr 23 '16 at 16:23
  • Try using select_ instead of select – gd047 Apr 23 '16 at 16:27
  • @GeorgeDontas Yes, the `select_` worked exactly in the `dplyr`, but the `i` was still not recognized as the raw name in the loop of `ggplot`: :.......`fill = factor(i)`......... –  Ming Apr 23 '16 at 16:36

2 Answers2

1

The tricky part is select_ and get():

The get() answers were from here : Remove quotes from a character vector in R

However, in my case,it did not work in the loop.I think it is probably due to double loops in my code (I am not sure).

Anyway, there is an alternative way to make it:

 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)

I got the idea from here Looping over variables in ggplot

Community
  • 1
  • 1
Ming
  • 181
  • 2
  • 10
0

If you need to keep ggplot output per SNP in a list, it is maybe better to use lapply which will output list, e.g.:

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
zx8754
  • 52,746
  • 12
  • 114
  • 209