You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中将字符串所有单词截断至5个字符或更短

R实现单词按需截断至5个字符以内

你可以通过拆分字符串→逐个处理单词→合并结果的思路来实现需求,具体代码如下:

  1. 定义输入数据:
data <- "The prisoner and his friend escaped but were later caught"
  1. 拆分字符串为独立单词的向量:
words_list <- strsplit(data, " ")[[1]]
  1. 对每个单词截取前5个字符(短于5个字符的单词保持原样):
truncated_words <- sapply(words_list, function(word) {
  substr(word, 1, min(nchar(word), 5))
})

这里用min(nchar(word), 5)动态控制截取长度:单词长度≤5时保留原长度,超过5时取前5个字符,解决了你之前统一截断的问题。

  1. 把处理后的单词合并回字符串:
final_result <- paste(truncated_words, collapse = " ")

运行后final_result的输出就是你期望的结果:

"The priso and his frien escap but were later caugh"

内容的提问来源于stack exchange,提问作者R.help.101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:32:36