R 使用 For 循环匹配字母和数字

R matching letters and numbers with a For Loop

我试图在每一行打印一个匹配的字母和数字。但是,代码会重复自身 26 x 26 次而不是 26 x 1 次。我希望到达第一个“z”后的中断会停止循环,但事实并非如此。

for (i in 1:26) {
  l = letters
  num = sapply(1:26, toOrdinal)
  print(paste0(l," is the ",num," letter of the alphabet."))
  if (l == "z") {
    break
  }
}

我写了一段备用代码,将数据放在矩阵中以控制打印,但我想让最上面的代码对我自己有启发。

#Create Data Matrix contain desired data to restrict continuous printing
matrix.letters <- matrix(nrow = 26, ncol = 3, dimnames = list(NULL, c("num", "letter", "ordinal")))
matrix.letters[,'num'] <- 1:26
matrix.letters[, 'ordinal'] <- sapply(1:26, toOrdinal)
matrix.letters[,'letter'] <- letters

#create index observation
letters.df <- as.data.frame(matrix.letters)

#YES - correct print achieved
for (i in nrow(letters.df)) {
  print(paste0(letters.df$letter," is the ",letters.df$ordinal, " letter of the alphabet."))
}

首先,请弄清楚非基础包。我在你的问题中推断出 `toOrdinal::toOrdinal 函数。

首先,您的问题是您正在循环,但您应该 索引 在代码的多个位置使用该循环计数:

for (i in 1:26) {
  l = letters[i]
  num = toOrdinal(i)
  print(paste0(l," is the ",num," letter of the alphabet."))
  if (l == "z") {
    break
  }
}
# [1] "a is the 1st letter of the alphabet."
# [1] "b is the 2nd letter of the alphabet."
# [1] "c is the 3rd letter of the alphabet."
# [1] "d is the 4th letter of the alphabet."
# [1] "e is the 5th letter of the alphabet."
# [1] "f is the 6th letter of the alphabet."
# [1] "g is the 7th letter of the alphabet."
# [1] "h is the 8th letter of the alphabet."
# [1] "i is the 9th letter of the alphabet."
# [1] "j is the 10th letter of the alphabet."
# [1] "k is the 11th letter of the alphabet."
# [1] "l is the 12th letter of the alphabet."
# [1] "m is the 13th letter of the alphabet."
# [1] "n is the 14th letter of the alphabet."
# [1] "o is the 15th letter of the alphabet."
# [1] "p is the 16th letter of the alphabet."
# [1] "q is the 17th letter of the alphabet."
# [1] "r is the 18th letter of the alphabet."
# [1] "s is the 19th letter of the alphabet."
# [1] "t is the 20th letter of the alphabet."
# [1] "u is the 21st letter of the alphabet."
# [1] "v is the 22nd letter of the alphabet."
# [1] "w is the 23rd letter of the alphabet."
# [1] "x is the 24th letter of the alphabet."
# [1] "y is the 25th letter of the alphabet."
# [1] "z is the 26th letter of the alphabet."

正如@Joe 在评论中所说,在您的原始代码中,paste0 得到 l(长度 26)和 num(长度 26),因此它返回正在打印的矢量(长度为 26)。我对你的 for 循环的第一个想法是低效的重新分配,因为 l = letters 每次通过都做完全相同的事情,与 num = sapply(..) 相同,所以那些可以移到循环之外。事实上,这可能会发生,代码略有不同:

Ls <- letters
nums <- sapply(1:26, toOrdinal)
for (i in 1:26) {
  print(paste0(Ls[i]," is the ",nums[i]," letter of the alphabet."))
  if (Ls[i] == "z") {
    break
  }
}

还有最后一点“不必要”的代码:break 在您期望 for(或 whilerepeat 或 ... ) 代码将继续太长。在这种情况下,我们知道 Ls[i] == "z" 在循环中第 26 次发生,无论如何它都会自行停止。所以对于这个循环, break 部分是不必要的。 (如果这只是流量控制的练习,那么这是一个很好的教训。)