1

I am trying to clean up my code, and I have a bit where I do the same thing multiple times with different samples. I am taking a random sample, and then plotting the SSE plot. If I copy and paste the code four time it works fine, but I just want to loop through and repeat it four times. Is for the wrong approach here? How can I accomplish this?

df <- iris

for (i in 1:4) {

  print(i)

####################################################

  # Random sample
  sample_df<- df[sample(nrow(df), 20),]

  # Remove ID variable
  sample_df$Species <- NULL

  # SSE plot
  fviz_nbclust(sample_df, kmeans, method = "wss")

####################################################  

}
pyll
  • 1,688
  • 1
  • 26
  • 44
  • 1
    Looks fine, does it work? I don't know where `fviz_nbclust` is from, but looks like it should work all right. If it uses `ggplot` or `grid` under the hood you might have to explicitly `print()` the plot. – Gregor Thomas Oct 30 '17 at 15:25
  • it does not work. If I simply copy and paste the code four times, it works. However, the loop produces no plots... – pyll Oct 30 '17 at 15:26
  • Looks like explicitly requesting the plot with `print()` did the trick...wondering why that's necessary though...Either way, thanks. – pyll Oct 30 '17 at 15:33
  • 1
    It's necessary because auto-printing is disabled inside loops and functions, and unlike base graphics `ggplot` only draws the plot when `print` is called. [This blog post talks about it some](https://www.data-imaginist.com/2017/beneath-the-canvas/). – Gregor Thomas Oct 30 '17 at 15:36

0 Answers0