网资酷

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 131|回复: 0

【Tidyverse优雅编程】R语言处理字符串或文本数据1:字符 ...

[复制链接]

6

主题

8

帖子

19

积分

新手上路

Rank: 1

积分
19
发表于 2022-9-23 10:55:33 | 显示全部楼层 |阅读模式
他们经常说:R语言处理字符串、文本数据不行
我说:就这?
我给他们来个 tidyverse 版本。
<hr/>先创建数据:
library(tidyverse)
df = tibble(
   item_id = 1001:1006,
   description = c("used car 3 years old", "brand new car",
                   "5-year-old used car", "used bicycle",
                   "car, 10k mileage, used", "car"),
   lot = c("A-124-X", "B-102-X", "A-039-Y",
           "A-200-Y", "B-120-Y", "B-025-X"),
   price = c(24000, 36000, "$18000", 1200, "12k", 14000))
df

1. 检查字符串是否包含特定的单词或字符序列


  • 筛选 description 列,包含 "used car" 的行
df %>%
  filter(str_detect(description, "used car"))


  • 筛选 description 列,包含 "used" 且包含 "car" 的行
df %>%
  filter(str_detect(description, "used"), str_detect(description, "car"))

2. 根据字符串的长度进行过滤


  • 筛选 description 列字符串长度 > 15 的行:
df %>%
  filter(str_count(description) > 15)

3. 基于字符串的第一个或最后一个字母进行过滤


  • 筛选 lot 列以 "A" 开头的行:
df %>%
  filter(str_starts(lot, "A"))


  • 筛选 lot 列以 "A-0" 开头的行:
df %>%
  filter(str_starts(lot, "A-0"))

4. 过滤非数字字符


  • 筛选 price 列只包含数字的行:
df %>%
  filter(!is.na(as.numeric(price)))

更好的做法(正则表达式,结果同上):
df %>%
  filter(!str_detect(price, "\\D"))注:若要选出带字符的,去掉 "!" 即可。
5. 计算单个字符或字符序列的出现次数


  • 统计 description 列 "used" 出现的次数:
df %>%
  mutate(n = str_count(description, "used"))

若要筛选出现次数小于 1 的行:
df %>%
  filter(str_count(description, "used") < 1)
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|网资酷

GMT+8, 2025-3-15 13:34 , Processed in 0.088740 second(s), 23 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表