《Machine Learning for Hackers》一书的合著者John Myles White近日接受了一个访谈。在访谈中他提到了自己在R中常用的几个扩展包,其中包括用ggplot2包来绘图,用glmnet包做回归,用tm包进行文本挖掘,用plyr、reshape、lubridate和stringr包进行数据预处理。这些包本博客大部分都有所介绍,今天就来看看这个遗漏的stringr包。
从名字就看得出,stringr包是用来处理字符串的。R语言本身的字符处理能力已经不错了,但使用起来并不是很方便。stringr包将原本的字符处理函数进行了打包,统一了函数名和参数。在增强功能基础上,还能处理向量化数据并兼容非字符数据。stringr包号称能让处理字符的时间减少95%。下面将其中的一些主要函数罗列一下。
library
(stringr)
# 合并字符串
fruit <-
c
(
"apple"
,
"banana"
,
"pear"
,
"pinapple"
)
res <-
str_c
(1:4,fruit,sep=
' '
,collapse=
' '
)
str_c
(
'I want to buy '
,res,collapse=
' '
)
# 计算字符串长度
str_length
(
c
(
"i"
,
"like"
,
"programming R"
,123,res))
# 按位置取子字符串
str_sub
(fruit,1,3)
# 子字符串重新赋值
capital <-
toupper
(
str_sub
(fruit,1,1))
str_sub
(fruit,
rep
(1,4),
rep
(1,4))<- capital
# 重复字符串
str_dup
(fruit,
c
(1,2,3,4))
# 加空白
str_pad
(fruit,10,
"both"
)
# 去除空白
str_trim
(fruit)
# 根据正则表达式检验是否匹配
str_detect
(fruit,
"a$"
)
str_detect
(fruit,
"[aeiou]"
)
# 找出匹配的字符串位置
str_locate
(fruit,
"a"
)
# 提取匹配的部分
str_extract
(fruit,
"[a-z]+"
)
str_match
(fruit,
"[a-z]+"
)
# 替换匹配的部分
str_replace
(fruit,
"[aeiou]"
,
"-"
)
# 分割
str_split
(res,
" "
)