You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言for循环计算iris数据集z-score时输出重复问题求助

问题原因

  • 你的循环遍历对象是iris$Sepal.Length的150个实际数值,会执行150次循环
  • 每次循环内部paste语句中使用了1:150,会单次生成150条拼接结果,最终总共输出150*150=22500条内容,就是你观察到的重复输出现象
  • 额外的性能问题:mean()和sd()的计算和循环无关,放在循环内部会重复计算150次,属于无效运算

修正后的循环写法

vetor <- iris$Sepal.Length
# 把固定值计算放在循环外减少冗余运算
mean_val <- mean(vetor)
sd_val <- sd(vetor)
# 遍历索引而非实际数值
for (i in seq_along(vetor)) {
  zscore <- (vetor[i] - mean_val)/sd_val
  print(paste("The z score number", i, "is", zscore))
}

更符合R语言习惯的向量化写法(无需循环)

vetor <- iris$Sepal.Length
zscores <- scale(vetor) # scale函数可直接计算z-score
paste("The z score number", seq_along(vetor), "is", zscores) |> print()

内容的提问来源于stack exchange,提问作者Yko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 13:27:03