3

I am trying to plot within a for loop in r, which is a very simple task in python. I would like 3 plots based on a parameter taking 3 different values.

my code


clust <- list(3,4,5)

for (i in clust)

set.seed(42)
k_clust = kmeans(
  college_scaled,
  centers = i,
  nstart = 25
  )

fviz_cluster(
  k_clust,
  data = college_scaled,
  main = "Colleges Segmented by Average Faculty Salary and Tuition Rates",
  geom= c("point","text"),
  labelsize= 8,
  pointsize= 1,
  ggtheme= theme_minimal()
)

For some reason this only plots centers = 5 instead of iterating through the loop and plotting 3,4, and 5. Why is this?

bismo
  • 1,257
  • 1
  • 16
  • 36

1 Answers1

3

I don't have college_scaled data to replicate your code, for block doesn't include both k_clust and fviz_cluster commands. Add {, } to keep both in the loop:

clust <- list(3,4,5)

for (i in clust)
{  
  set.seed(42)
k_clust = kmeans(
  college_scaled,
  centers = i,
  nstart = 25
)

print(
  fviz_cluster(
    k_clust,
    data = college_scaled,
    main = "Colleges Segmented by Average Faculty Salary and Tuition Rates",
    geom= c("point","text"),
    labelsize= 8,
    pointsize= 1,
    ggtheme= theme_minimal()
  )
)
}

Edit: added print based starja on reminder in comments.

Dan
  • 494
  • 2
  • 14