0

I am trying to plot 9 barplots in a 3X3 matrix in R using base-R wrapped inside a for loop. (I am working on a workhorse solution for visualizing every column before I begin working on manipulating data) Below is the code:

library(ISLR); 
library(ggplot2);
# load wage data
data(Wage)
par(mfrow=c(3,3))
for(i in 1:(dim(Wage)[2]-2)){
plot(Wage[,i],main = paste0(names(Wage)[i]),las = 2)
}

But unfortunately can't do properly for first 2 columns because they are numeric and actually needs a histogram. I get it that I need to fit if-else condition somewhere inside for() statement but that is giving me errors. below is the output where first 2 columns are plotted wrong. (Age and year are actually numeric and I may need to use them in X-axis instead of defaulting them to y). Kindly requesting to suggest an edit/hack? I also learnt that I cant' use par() when I am wrapping ggplot inside for so I had to use base-R otherwise ggplot would have been great aesthetically.

enter image description here

Scott Grammilo
  • 1,229
  • 4
  • 16
  • 37
  • 4
    `?is.numeric; ?is.factor` – d.b Oct 24 '17 at 15:36
  • 1
    You can use `ggplot` and use `gridExtra::grid.arrange` instead of `par`. [The link I posted on your last question shows how to do this](https://stackoverflow.com/q/1249548/903061), and gives several other methods too. – Gregor Thomas Oct 24 '17 at 15:40
  • Actually I can resolve first 2 columns if I just know them beforehand. and plot them separately like below but thinking what in a situation where i have multiple columns and dont know which ones need to be treated differently. This is my desired output but without doing any pre-preliminary checks. ` `par(mfrow=c(3,3))` `for(i in 1:2){ hist(Wage[,i],main = paste0(names(Wage)[i]),las = 2) }` `for(i in 3:(dim(Wage)[2]-2)){` `plot(Wage[,i],main = paste0(names(Wage)[i]),las = 2) }` ` – Scott Grammilo Oct 24 '17 at 15:42
  • 2
    I don't understand where you are stuck. As d.b says you can use `is.numeric` or `is.factor` to test what the current column type is and run whatever command you want. I've pointed out resources for using ggplot if you would prefer that. Are you familiar with `if()`? Essentially you want `for (i in 1:ncol(Wage)) { if(is.numeric(Wage[, i])) {hist(...)} if( is.factor(Wage[, i]) {plot(...)} }` – Gregor Thomas Oct 24 '17 at 15:54
  • Thanks d.b and @Gregor. really appreciate. I realized how to use if. That works perfect. Thanks once again :) But yeah I will look into grid.arrange option as well and see if I can get it. – Scott Grammilo Oct 24 '17 at 16:28

0 Answers0