繁体   English   中英

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 function 。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM