如何在R语言中用函数实现循环,按位置或词长输出单词长度信息
R语言单词长度遍历与匹配实现方案
首先定义你的字符向量:
sentence <- c("Learning", "loops", "in", "R", "is", "not", "that", "bad")
1. 遍历所有单词输出长度信息
用for循环逐个处理每个单词,结合nchar()计算长度后拼接提示文本:
for (word in sentence) { word_length <- nchar(word) cat(paste0(word, "有", word_length, "个字母\n")) }
运行后会逐个输出:
Learning有8个字母
loops有5个字母
in有2个字母
R有1个字母
is有2个字母
not有3个字母
that有4个字母
bad有3个字母
2. 根据指定长度筛选并输出匹配单词
先设定目标长度,筛选出符合条件的单词后循环输出:
# 设定目标长度 target_length <- 3 # 筛选匹配长度的单词 matched_words <- sentence[nchar(sentence) == target_length] # 输出结果 if (length(matched_words) > 0) { for (word in matched_words) { cat(paste0(word, "有", target_length, "个字母\n")) } } else { cat(paste0("没有找到长度为", target_length, "的单词\n")) }
比如设定target_length=3时,输出:
not有3个字母
bad有3个字母
3. 遍历所有出现过的单词长度并分组输出
如果要遍历向量中所有唯一的单词长度,并按长度分组输出对应单词:
# 获取所有唯一的单词长度 unique_lengths <- unique(nchar(sentence)) # 遍历每个唯一长度 for (len in unique_lengths) { cat(paste0("\n--- 长度为", len, "的单词 ---\n")) current_words <- sentence[nchar(sentence) == len] for (word in current_words) { cat(paste0(word, "有", len, "个字母\n")) } }
运行后会按不同长度分组展示结果。
内容的提问来源于stack exchange,提问作者Adar Sheere
相关产品推荐
相关产品推荐

