在R语言中用for循环绘制多个图表

3
我尝试在R语言的循环中绘制图形,这在Python中非常简单。我希望基于一个参数取3个不同的值得到3个图形。
我的代码:

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()
)

由于某些原因,这个代码只绘制了centers = 5,而没有循环迭代并绘制3、4和5。为什么会这样?

1
for循环体的花括号在哪里? - cdalitz
我尝试了那个,但没有任何图表绘制出来。如果没有它们,只会生成一个图表。@cdalitz - bismo
1
将结果保存在列表中。 - KM_83
1个回答

3

我没有 college_scaled 数据来复制您的代码,因为该块不包括 k_clustfviz_cluster 命令。加入 {, } 以保持这两个命令在循环中:

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()
  )
)
}

编辑: 在评论中加入了基于starja的打印提醒。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接