r - 在R中包含多个单词的列中查找最长的单词
问题描述
我正在使用 nycflights13 包中的机场数据集。我想从第二列中找到长度最长的单词,即名称
我尝试了两种方法
在 airports$name 上使用 stringr 中的 strsplit + 边界函数,但现在不知何故能够有效地完成这项工作。
使用 word 函数,但它只取名称中的第一个单词
library(tidyverse) library(nycflights13) airport <- nycflights13::airports strsplit(word(airport$name),boundary("word"))
解决方案
这是一种使用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
推荐阅读
- raspberry-pi - 设置您的 Raspberry Pi 环境以制作 Alexa 时出现 Raspberry pi 3 错误
- python - Pandas Dataframe:如何使用 NaN 管理列的自动浮点转换
- javascript - 如何遍历 JSON 并向对象添加值
- xtermjs - 如何在 xterm.js 中使用滚动线
- datepicker - 赛普拉斯:从当前日期选择 2 周前的日期
- firebase - 将 Firebase 身份验证用户从一种登录方法迁移到另一种
- flutter - 实时 OCR 颤振
- unit-testing - 如何使用 Vue 3 Composition API 在测试中获取 Ref 值
- react-typescript - 如何在反应打字稿项目中设置 setupProxy.js 文件
- swift - 当用户在 SwiftUI 中使用 AsyncImageView 查看 TabView 页面轮播中的第一张图片时,如何加载下一张图片?