Home > OS >  For Loop In R not working with Plot function
For Loop In R not working with Plot function

Time:05-24

I Am trying out a way to figure out how i could print multiple plots at once with a for loop , as i am super new to R i can't seem to find a way to do this

I Have 40 Principle components that i would like to plot through for loop, but i can only do it individually by calling the function every time ; for loop just does nothing

Below is the function to show or plot principle components

showPrincipalComponents <- function(PCNumber) {
tidied_pca %>%
filter(PC == PCNumber) %>%
top_n(11, abs(Contribution)) %>%
mutate(Tag = reorder(Tag, Contribution)) %>%
ggplot(aes(Tag, Contribution, fill = Tag))  
geom_col(show.legend = FALSE, alpha = 0.8)  
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5), 
      axis.ticks.x = element_blank())   
labs(x = "Personal attributes",
     y = "Principal Component Importance")

}

This Works:

showPrincipalComponents(comp[1]) 
showPrincipalComponents(comp[2]) 
showPrincipalComponents(comp[3]) 
showPrincipalComponents(comp[4]) 

This Does Not(executes without returning anything):

x=1:40
for (i in x){showPrincipalComponents(comp[i])}

Any Help would be appreciated

CodePudding user response:

You have to do two things to make it work in a for loop.

(1) As @neilfws already points out in the comments, the output of the for loop needs to be assiged (e.g. out[[i]] <-).

(2) Since ggplot uses lazy evaluation only doing (1) will yield the same plot forty times (always the last plot, i = 40). If you want to stick to a for loop instead of an lapply you could wrap the function call into eval(bquote()) and evaluate .(i).

x <- 1:40
out <- vector("list", length = length(x))

for (i in x) {
  out[[i]] <- eval(bquote(
    showPrincipalComponents(comp[.(i)])
  ))
}
out
  • Related