2

I have a dataframe in r and I want to provide the boxplot of each integer variable. I have 34 variables so it's useless to do them manually, thus I opted for a for loop but it only returns the first boxplot of the first variable. Here's the code I used:

for (i in 1:34) {
  if (class(data[,i])== "integer") {
    return(boxplot(data[,i])) 
  } 
}

ameni
  • 31
  • 3

2 Answers2

3

Your code stops, because return is called.

Sadly, in R you cannot store base plots in a variable without using additional libraries. But if you use ggplot2 for creating your boxplots, you can store them into a list:

plots <- list()
a <- 1
for (i in 1:34) {
  if (class(data[,i]) == "integer") {
    plots[[a]] <- boxplot(data[,i])) 
    a <- a + 1
  } 
}

Subsequently, you can plot them all together in a grid by using grid.arrange from ggplot2. The following code should do the trick (big thanks to Josh O'Brien):

library(gridExtra)

n <- length(plots)
nCol <- floor(sqrt(n))
do.call("grid.arrange", c(plots, ncol=nCol))
georg-un
  • 1,123
  • 13
  • 24
1

To elaborate a bit on georg_un's answer:

Calling return() will stop execution of all cycles.

Consider this example:

for (i in 1:500) {

  for (y in 1000:1) {

      cat(paste("big", i, "small", y))

      return("the end is nigh!")
  }

} 

This will not print 500 000 items (500x big cycle, 1000x small cycle) but only one.
The return() will stop everything...

Return is normally not used in context of for cycles, but for early termination of functions.

Jindra Lacko
  • 7,814
  • 3
  • 22
  • 44