提取字符串中最长的单词 [英] Extract longest word in string
本文介绍了提取字符串中最长的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果可能,我想使用 tidyverse
包查找并提取字符串中最长的单词.
I would like to find and extract the longest word of a string, if possible using a tidyverse
package.
library(tidyverse)
tbl <- tibble(a=c("ab cde", "bcde f", "cde fg"), b=c("cde", "bcde", "cde"))
tbl
# A tibble: 3 x 1
a
<chr>
1 ab cde
2 bcde f
3 cde fg
我要找的结果是:
# A tibble: 3 x 2
a b
<chr> <chr>
1 ab cde cde
2 bcde f bcde
3 cde fg cde
与我发现的问题最接近的帖子是:字符串中最长的单词一>.有没有人有更简单的方法的想法?
The closest post to the question I have found is this: longest word in a string. Does anyone have an idea for an even simpler way?
推荐答案
使用基础 R 的解决方案:
Solution using base R:
# Using OPs provided data
tbl$b <- sapply(strsplit(tbl$a, " "), function(x) x[which.max(nchar(x))])
说明:
- 将每一行拆分成单词 (
strsplit
) - 确定字长(
nchar
) - 选择一行中最长的单词 (
which.max
)
这篇关于提取字符串中最长的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文