Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I want to lapply to produce many box plots in R. When I create the box plots using a ggplot function I get the correct output. But when I try to pass the box plot function through the lapply using colnames the function does not work as supposed to do. 

doPlot = function(var1) {

  # Create the plot object

  ggobj = ggplot(wdbc_train, aes(x = diagnosis,y=var1)) + geom_boxplot()

  # Add some titles and axis labels

  ggobj = ggobj + ggtitle(var1) + xlab("diagnosis") + 

    ylab(var1)

}

lapply(colnames(wdbc_train),doPlot)

1 Answer

0 votes
by (108k points)

For that what you have to do is to get the data from the named variable, refer to the below code:

doPlot = function(var1) {

  # Create the plot object 

  ggobj = ggplot(wdbc_train, aes(x = diagnosis, y=get(var1))) + 

    geom_boxplot()

  # Add some titles and axis labels 

  ggobj = ggobj + ggtitle(var1) + xlab("diagnosis") + ylab(var1) 

}

doPlot = function(var1) {

  # Create the plot object 

  ggobj = ggplot(iris, aes(x = Species, y=get(var1))) + geom_boxplot()

  # Add some titles and axis labels 

  ggobj = ggobj + ggtitle(var1) + xlab("Species") + ylab(var1) 

}

p <- lapply(colnames(iris)[-5], doPlot)

library(gridExtra)

grid.arrange(grobs=p)

If you are a beginner and want to know more about R then do check out the following R programming tutorial

Related questions

Browse Categories

...