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

时间:2021-04-10 16:02:49

标签: r loops matrix letter ordinal

我试图在每一行打印一个匹配的字母和数字。但是,代码重复了 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."))
}

1 个答案:

答案 0 :(得分:2)

首先,请清楚非基础包。我在你的问题中推断 `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 部分是不必要的。 (如果这只是一个流程控制练习,那么这是一个很好的教训。)