R – Multiple plots using loops in R

dataframeloopsplotr

I'm still trying to get my head around using loops to plot in R. I would like to plot (any plot to visualise the data will do) columns z_1 against z_2 in the data frame below according to the different names in column x_1.

x_1 <- c("A1", "A1","A1", "B10", "B10", "B10","B10", "C100", "C100", "C100")


z_1 <- rnorm(10, 70) 

z_2 <- rnorm(10, 1.7)

A <- data.frame(x_1, z_1, z_2)

As such, I would like to end up with three different plots; one for category A1, one for B10 and another for C100. I can do this using three different codes but I would like to be able to use a loop or any other single code to execute all three plots on the same page. In reality, I have a large dataset (4,000 rows) and would like to plot a couple of IDs on a page (say 5 on a page).

I hope this makes sense. Thanks for your help.

Here's my attempt at plotting them individually:

for A1:

data_A1 <- A[which(A$x_1 == "A1"), ]
plot(data_A1$z_2, data_A1$z_1)

I also tried something like this but getting error messages

for ( i in A$x_1[[i]]){

plot(A[which(A$x_1==A$x_1[[i]]), ], aspect = 1)
}

Best Answer

A simple approach with loops would be

for (cat in unique(x_1)){
  d <- subset(A, x_1 == cat)
  plot(d$z_1, d$z_2)
}

unique(x_1) gets you all the unique values of x_1. Then, for each of these values get a corresponding subset and use this subset for plotting.