假设我们有一个包含单词的向量 words,我们的目标是找到长度为 n 的单词并打印出来。
下面是一个使用 for 循环的示例代码:
words <- c("apple", "banana", "cherry", "date", "elderberry", "fig")
n <- 5
for (i in 1:length(words)) {
if (nchar(words[i]) == n) {
print(paste("Word:", words[i], "is of length", n))
}
}
此代码将遍历单词向量并打印出长度为 n 的每个单词及其长度。
我们还可以使用 sapply 函数进一步简化代码:
words <- c("apple", "banana", "cherry", "date", "elderberry", "fig")
n <- 5
words_n <- sapply(words, function(x) {
if (nchar(x) == n) {
paste("Word:", x, "is of length", n)
} else {
""
}
})
print(words_n[words_n != ""])
此代码将使用 sapply 函数创建一个新的向量 words_n,它包含所有长度为 n 的单词。最后,我们打印出 words_n 中不为空的值。
输出结果如下:
[1] "Word: apple is of length 5"
[2] "Word: fig is of length 5"