首页 > 解决方案 > 在R中包含多个单词的列中查找最长的单词

问题描述

我正在使用 nycflights13 包中的机场数据集。我想从第二列中找到长度最长的单词,即名称

我尝试了两种方法

  1. 在 airports$name 上使用 stringr 中的 strsplit + 边界函数,但现在不知何故能够有效地完成这项工作。

  2. 使用 word 函数,但它只取名称中的第一个单词

     library(tidyverse)
     library(nycflights13)
     airport <- nycflights13::airports
    
     strsplit(word(airport$name),boundary("word"))
    

标签: rdplyrtidyversestringr

解决方案


这是一种使用purrr::map. name首先,按空格分割列。然后将自定义函数应用于创建的列表。我们可以使用[将每个列表元素中的向量子集为最长的单词。nchar我们可以通过应用到每个元素来确定最长的单词。which.max可以告诉我们哪个最长。

_char版本map将返回一个字符向量。

library(tidyverse)
airport %>%
   mutate(longest = map_chr(strsplit(name," "),
                            ~ .x[which.max(nchar(.x))]),
          wordlength = nchar(longest)) %>%
   select(name,longest,wordlength)
## A tibble: 1,458 x 3
#   name                           longest      wordlength
#   <chr>                          <chr>             <int>
# 1 Lansdowne Airport              Lansdowne             9
# 2 Moton Field Municipal Airport  Municipal             9
# 3 Schaumburg Regional            Schaumburg           10
# 4 Randall Airport                Randall               7
# 5 Jekyll Island Airport          Airport               7
# 6 Elizabethton Municipal Airport Elizabethton         12
# 7 Williams County Airport        Williams              8
# 8 Finger Lakes Regional Airport  Regional              8
# 9 Shoestring Aviation Airfield   Shoestring           10
#10 Jefferson County Intl          Jefferson             9
## … with 1,448 more rows

推荐阅读