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

如何在R中用For、While、Repeat函数高效打印指定重复序列?

问题背景

你需要用R中的for、while和repeat循环打印以下结果:

[1] 9 9 9 9 9
[1] 7 7 7
[1] 5
[1] 3 3 3
[1] 1 1 1 1 1

你已经写出了可行代码,但觉得写法不够自然,希望找到更简洁易懂的实现方式。


优化思路

原代码的核心是通过索引和额外向量来映射“数值-打印次数”的关系,逻辑比较绕。我们可以直接把要打印的数值和对应的次数显式定义出来,让循环逻辑一目了然。


For循环优化

直接遍历数值和次数的配对,逻辑清晰,不需要复杂的条件判断:

# 定义要打印的数值和对应的次数
target_values <- c(9, 7, 5, 3, 1)
print_counts <- c(5, 3, 1, 3, 5)

for (idx in seq_along(target_values)) {
  print(rep(target_values[idx], print_counts[idx]))
}

这样写的好处是,任何人一看代码就知道每个数值要重复打印多少次,完全不需要猜索引对应的含义。

While循环优化

同样用显式的数值和次数配对,避免依赖模糊的索引映射:

target_values <- c(9, 7, 5, 3, 1)
print_counts <- c(5, 3, 1, 3, 5)
current_idx <- 1

while (current_idx <= length(target_values)) {
  print(rep(target_values[current_idx], print_counts[current_idx]))
  current_idx <- current_idx + 1
}

如果想保留“从9递减2”的原始逻辑,也可以这么写:

current_val <- 9
print_counts <- c(5, 3, 1, 3, 5)
count_idx <- 1

while (current_val >= 1) {
  print(rep(current_val, print_counts[count_idx]))
  current_val <- current_val - 2
  count_idx <- count_idx + 1
}

Repeat循环优化

和上面的思路一致,把逻辑简化,让break条件和打印逻辑更直观:

target_values <- c(9, 7, 5, 3, 1)
print_counts <- c(5, 3, 1, 3, 5)
current_idx <- 1

repeat {
  # 超出范围就退出循环
  if (current_idx > length(target_values)) break
  print(rep(target_values[current_idx], print_counts[current_idx]))
  current_idx <- current_idx + 1
}

或者保留递减逻辑的版本:

current_val <- 9
print_counts <- c(5, 3, 1, 3, 5)
count_idx <- 1

repeat {
  if (current_val < 1) break
  print(rep(current_val, print_counts[count_idx]))
  current_val <- current_val - 2
  count_idx <- count_idx + 1
}

这些优化后的代码去掉了不必要的索引计算和next语句,把“要打印什么、打印多少次”的核心逻辑直接展现出来,可读性和维护性都更强啦!

内容的提问来源于stack exchange,提问作者Daniel HyunHo Shin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:52:25