1) stringr 计算输入的每个组件中的单词数,并将其或 3 中的较小者用作要返回的单词数。
library(stringr)
word(sentences, end = pmin(str_count(sentences, "\\w+"), 3))
## [1] "Jane saw a" "Jane sat down" "Jane sat" "Jane"
2) stringr solution 2 在末尾附加一些虚拟词,取前 3 个词并剪掉剩下的任何虚拟词。
sentences %>%
str_c("@ @ @") %>%
word(end = 3) %>%
str_replace(" *@.*", "")
## [1] "Jane saw a" "Jane sat down" "Jane sat" "Jane"
3a) Base R 与 (1) 相同的想法可以这样转换为 Base R:
Word <- function(x, end) do.call("paste", read.table(text = x, fill = TRUE)[1:end])
unname(Vectorize(Word)(sentences, end = pmin(lengths(strsplit(sentences, " ")), 3)))
## [1] "Jane saw a" "Jane sat down" "Jane sat" "Jane"
3b) 与 (2) 相同的想法可以像这样转换为基础 R。 Word 来自 (3a)。
sentences |>
paste("@ @ @") |>
Word(end = 3) |>
sub(pattern = " *@.*", replacement = "")
## [1] "Jane saw a" "Jane sat down" "Jane sat" "Jane"
更新
(1) 被简化,旧的 (1) 现在是 (2)。 (3a) 和 (3b) 现在是 Base R 对应项。