【发布时间】:2019-08-27 02:19:42
【问题描述】:
我希望将字符串拆分为 3 个字符的 ngram - 例如,HelloWorld 将变为“Hel”、“ell”、“llo”、“low”等 我将如何使用 R 实现这一目标?
在 Python 中,它会使用 range 函数进行循环 - 例如[myString[i:] for i in range(3)]
有没有一种巧妙的方法来循环使用stringr(或其他合适的函数/包)将单词标记为向量来遍历字符串的字母?
例如
dfWords <- c("HelloWorld", "GoodbyeMoon", "HolaSun") %>%
data.frame()
names(dfWords)[1] = "Text"
我想生成一个新列,其中包含一个标记化文本变量的向量(最好使用dplyr)。然后可以稍后将其拆分为新列。
【问题讨论】:
-
很少使用
substring而不是substr,它循环所有输入 -substring("HelloWorld",1:8,3:10)- 但这仅适用于长度为 1 的向量 - 因为substring(c("HelloWorld","ABC"),1:8,3:10)不没有按预期工作。这样就够了吗? -
@thelatemail 对我来说看起来不错。