Mac版R语言(五)使用正则表达式(Regular Expressions)提取数据信息

13 篇文章 2 订阅
12 篇文章 8 订阅

        通常情况下,我们收集到的数据可能是混合字段或非标准化的数据集。这些数据往往需要我们通过一定的方式,提取出其中特定维度或字段的信息,并以此创建新的数据集。

        在低维数据中,可以使用剔除行列的方式选取特定字段的信息;或者直接进行行列选取的方法(具体实现方式,详见(三)数据的导入点击打开链接),但是当数据库是高维度数据库、空间数据库、非标准化数据库时,如HDF5,普通的删除行列方式提取信息的效率非常低下。本节内容,是通过正则表达式(Regular Expressions)实现信息的精确提取,本章内容的关键名词将全部实现中英文双标,涵盖以下几个要点:

  • 指定信息提取/指定数据类型提取
  • 混乱数据集的特定信息提取
  • 非标准化数据集的特定信息提取
以上实现方式全部基于Regular Expression。

一. 指定信息提取/指定数据类型提取

> setwd("~/Desktop")
> getwd()
[1] "/Users/Apple/Desktop"
> library(stringr)  #需提前安装 stringr 包,具体安装方法,请见第一篇博客内容点击打开链接
> strings <- c(
+ "apple",
+ "219 733 8965",
+ "329-293-8753",
+ "Work:579-499-752;Home:543.355.3679"
+ )

> phone <- "([1-9][0-9]{2}[- .][0-9]{3}[- .][0-9]{4})"  #phone的Pattern matching,第一个数2~9,第二个数0~9有两个,分隔符为-空格.
> str_detect(strings,phone)     #strings中哪些项符合phone的regular expression匹配,返回相应位置逻辑值
[1] FALSE  TRUE  TRUE  TRUE
>  str_subset(strings,phone)     #str_subset() returns the elements of a character vector that match a regular expression 
[1] "219 733 8965"     "329-293-8753"                       
[3] "Work:579-499-7527;Home:543.355.3679"
> str_extract(strings,phone)      #str_extract() extracts text corresponding to the first match, returning a character vector
[1] NA             "219 733 8965" "329-293-8753" "579-499-7527"
> str_extract_all(strings,phone,simplify = T)   #str_extract_all() extracts all matches and returns a list of character vectors.
     [,1]           [,2]          
[1,] ""             ""            
[2,] "219 733 8965" ""            
[3,] "329-293-8753" ""            
[4,] "579-499-7527" "543.355.3679"
> str_split(stringrs,"[- .]")    str_split() splits a string into a variable number of pieces and returns a list of character vectors.
[[1]]
[1] "apple"


[[2]]
[1] "219"  "733"  "8965"


[[3]]
[1] "329"  "293"  "8753"


[[4]]
[1] "Work:579"      "499"           "7527;Home:543" "355"           "3679"         



  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值