当前位置: 动力学知识库 > 问答 > 编程问答 >

R: how to pass a list of plots from a function and access the contents?

问题描述:

I am creating some plots in a function and then I pass them to the regular code. There are no error messages but when I run the code, the code is not receiving the plot - the plots do not appear after returning from the function.

This is my code. Please let me know what I am doing wrong so it can work.

Thanks

library(dplyr)

library(stringr)

library(ggplot2)

library(reshape2)

require(grid)

create_plots <- function(selection) {

temp_plot <- list()

if(selection == 1)

{

temp_plot[[1]] <- hist(mtcars$mpg,

main="my histogram",

xlab="xlabel",

ylab="ylabel")

return(temp_plot)

}

if(selection == 2)

{

temp_plot[[1]] <- ggplot(mtcars, aes(x=mtcars$mpg)) +

geom_histogram(binwidth=0.10, colour="black", fill="white") +

ggtitle ("frequency!!") +

labs(x=mpg, y="frequency")

return(temp_plot)

}

if(selection == 3)

{

temp_plot[[1]] <- barplot(mtcars$mpg,

main="my barplot",

xlab="xlabel",

ylab="ylabel")

return(temp_plot)

}

}

plot_list2 <- list()

plot_list3 <- list()

plot_list2[[1]]<-create_plots(1) #ok

plot(plot_list2[[1]][[1]]) # ok

plot_list2[[2]]<-create_plots(2) #ok

plot(plot_list2[[2]][[1]]) #ok

plot_list2[[3]]<-create_plots(3) #ok

plot(plot_list2[[3]][[1]]) #prints some strange plot not my barplot, why?

plot_list3<-create_plots(1) #ok

plot(plot_list3[[1]]) #ok

plot_list3<-create_plots(2)

plot(plot_list3[[2]]) #subscript out of bounds error for a list of TWO items???

plot_list3<-create_plots(3) #ok

plot(plot_list3[[3]]) #subscript out of bounds error for a list of TWO items???

分享给朋友:
您可能感兴趣的文章:
随机阅读: