提取字符串中最长的单词

Extract longest word in string

我想找到并提取字符串中最长的单词,如果可能的话使用 tidyverse 包。

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

最接近 post 我发现的问题是:longest word in a string。有没有人有更简单的方法的想法?

使用基础 R 的解决方案:

# Using OPs provided data
tbl$b <- sapply(strsplit(tbl$a, " "), function(x) x[which.max(nchar(x))])

解释:

  • 将每行拆分为单词 (strsplit)
  • 确定字长(nchar)
  • Select 哪个单词在一行中最长 (which.max)

这是@PoGibas 答案的可能 tidyverse 版本

library(tidyverse)
tbl <- tibble(a=c("ab cde", "bcde f", "cde fg"))

tbl %>% 
  mutate(b = map_chr(strsplit(a, " "), ~ .[which.max(nchar(.))]))

#> # A tibble: 3 x 2
#>        a     b
#>    <chr> <chr>
#> 1 ab cde   cde
#> 2 bcde f  bcde
#> 3 cde fg   cde