R: Loop over list of data frames and create plot of columns with constraints

loops, plot, r

Solution

Should you be doing something like this? -

# Loop over list of data frames and create plots
for (i in seq(titlenames)) {
  plot(x=(l[[i]]$a[l[[i]]$c==0]),y=(l[[i]]$b[l[[i]]$c==0]),main="",xlab="",ylab="")
  title(main=titlenames[i])
}

I posted as answer, the comment would be ugly and hard to read. Basically, I've removed the j loop and am tracking everything with 1 which now loops over 1:n, and not `l`.

Problem

I want to loop over a list of numeric data frames and create plots for specific columns of each data frame using a for loop. I have a working code but the result is odd. I would expect only two plots to be created but R creates four and I can simply not understand why especially because when I use print instead of plot, he is printing the values I would expect. Below a small example of the much bigger dataset. Any idea is much appreciated. Many thanks! ``` # Create data a <- c(1,2,3,4,5) b <- c(6,7,8,9,10) c <- c(0,0,0,1,0) d <- c(1,2,3,4,5,6,7,8,9,10) e <- c(11,12,13,14,15,16,17,18,19,20) f <- c(0,0,0,0,0,0,0,1,0,0) # Create data frames df1 <- data.frame(cbind(a,b,c)) df2 <- data.frame(cbind(d,e,f)) names(df2) <- c("a","b","c") # Create list of data frames l <- list(df1,df2) # Create titles for plots titlenames <- c("Graph 1","Graph 2") # Loop over list of data frames and create plots for (i in l){ for(j in titlenames) { plot(x=(i$a[i$c==0]),y=(i$b[i$c==0]),main="",xlab="",ylab="") title(main=paste(j)) }} ```

Original source