stringr字符處理 - 簡書 (jianshu.com)
dplyr表格操作 - 簡書 (jianshu.com)
在正式學(xué)習(xí)
stringr、dplyr為代表的tidyrverse核心系列包時,有必要先了解下正則表達(dá)式以及管道符的相關(guān)知識。
正則表達(dá)式
-
.: 可以匹配除換行符外的任意字符 -
?:表示前面的模式(無特殊情況即單個字符)重復(fù)0 次或 1 次。
+:1 次或多次。
*:0 次或多次。
{n}:指定匹配 n 次。
{n,}:指定匹配 n 次或更多次。
{,m}:指定最多匹配 m 次。
{n, m}:指定匹配 n 到 m 次 -
^從字符串開頭進(jìn)行匹配
$從字符串末尾進(jìn)行匹配。 -
\d:匹配數(shù)字
\s:可以匹配任意空白符
\b:匹配單詞間的邊界
創(chuàng)建包含
\(例如\d、\s...)的正則表達(dá)式,需要在字符串中對\進(jìn)行轉(zhuǎn)移,即\\d、\\s。其實只要記住\\本質(zhì)上代表\即可。
匹配特殊字符示例
如果只是想匹配字符串本身的含義,fixed(正則表達(dá)式)可將正則表達(dá)式相關(guān)字符當(dāng)作純文本字符看待。
[abc]:可以匹配a、b,或c
[^abc]:可以匹配除a、b,c外的任意字符
[a-z]: 匹配任意小寫字母;[A-Z]:任意大寫字母;[A-z]:任意字母
|表示或,常搭配小括號,例如gr(e|a)y表示匹配grey或者gray[:digit:]:匹配數(shù)字
[:alpha:]:匹配字母
[:lower:]:匹配小寫字母
[:upper:]:匹配大寫字母
[:alnum:]:匹配字母/數(shù)字
[:punct:]:匹配標(biāo)點(diǎn)符號
[:blank:]:匹配空格、tab
[:space:]:匹配空格、tab、換行符最后的話,
()小括號可以用于表示分組,\1表示回溯引用第一個分組,具體用法可參考下面的str_match()函數(shù)的介紹。
fruit = c("apple","banana","pear","pineapple")
#查找具有ABAB模式的字符串
str_view(fruit,"(.)(.)\\1\\2", match = T)

注意:默認(rèn)的正則匹配方式都是“貪婪的”,即正則表達(dá)式會在符合規(guī)則的前提下匹配盡量長的字符串。通過在正則表達(dá)式后面添加一個
?,你可以將匹配方式更改為“懶惰的”,即匹配盡量短的字符串。
管道符%>%
- magrittr包提供的管道符語法對于R語言的代碼處理過程大大提高了效率,可通過下述方式查看內(nèi)置官方文檔;
?magrittr::`%>%
- 在加載
dplyr包時會自動加載magrittr包,從而便捷的使用管道符操作; -
管道符的含義理解,如下圖所示;
- 相關(guān)筆記可參考 https://zhuanlan.zhihu.com/p/29845549
stringr字符處理
1、字符串向量特征匹配
2、字符串特征匹配(取子集)
3、字符串的替換修改
4、字符串格式相關(guān)
5、字符串拼接與拆分
library(stringr)
https://github.com/rstudio/cheatsheets/blob/master/strings.pdf
1、字符串向量特征匹配
對于一個字符串向量,判斷其中哪些字符串是否具有給定的模式特征
- 1.1
str_detect():判斷每個字符串是否具有匹配模式,返回等長的邏輯值向量
fruit <- c("apple", "banana", "pear", "pinapple")
str_detect(fruit, "a") #包含a的字符串
str_detect(fruit, "a", negate = T) #不包含a的字符串
str_detect(fruit, "^a") #以a開頭的字符串
str_detect(fruit, "[aeiou]") #含有aeiou其中任意一個字符的字符串
- 1.2
str_starts()/str_ends():判斷每個字符串的開頭/結(jié)尾是否具有匹配模式,同樣返回等長的邏輯值向量
fruit <- c("apple", "banana", "pear", "pinapple")
str_starts(fruit, "p")
str_ends(fruit, "e")
- 1.3
str_which()/str_subset():判斷向量里的哪個字符串具有匹配模式;前者返回數(shù)字序號,后者返回具體的字符串
# str_which == which(str_detect(x, pattern))
# str_detect == x[str_detect(x, pattern)]
fruit <- c("apple", "banana", "pear", "pinapple")
str_subset(fruit, "a")
str_which(fruit, "a")
- 1.4
str_locate(): 返回匹配的模式在字符串的起始位置
fruit <- c("apple", "banana", "pear", "pineapple")
str_locate(fruit, "a")
str_locate_all(fruit, "a")
- 1.5
str_count():返回每個字符串內(nèi)有多少個符合匹配模式組成
fruit <- c("apple", "banana", "pear", "pineapple")
str_count(fruit, "a")
str_count(fruit, c("a", "b", "p", "p")) #向量化操作
2、字符串特征匹配(取子集)
- 2.1
str_sub():指定字符串的起始位置提取
hw <- "Hadley Wickham"
str_sub(hw, 1, 6)
str_sub(hw, -3, -1)
- 2.2
str_extract(): 提取字符串里的特征模式
shopping_list <- c("apples x4", "bag of flour", "bag of sugar", "milk x2")
str_extract(shopping_list, "\\d") #提取數(shù)字
str_extract(shopping_list, "[a-z]+") #提取1至多個小寫字母
str_extract(shopping_list, "[a-z]{1,4}") #貪婪匹配
str_extract(shopping_list, "[a-z]{1,4}?") #懶惰匹配
str_extract(shopping_list, "\\b[a-z]{1,4}\\b") #提取特征模式的單詞
str_extract(shopping_list, fixed("\\b[a-z]{1,4}\\b")) #fixed可將正則表達(dá)式視為普通字符串
#str_extract 默認(rèn)只提取字符串里第一個符合的模式
#str_extract_all可以提取全部的匹配
str_extract_all(shopping_list, "[a-z]+")
str_extract_all(shopping_list, "\\b[a-z]+\\b")
- 2.3
str_match(): 可分組提取字符串里的特征模式,更加靈活。
搭配括號使用,可提取分組的內(nèi)容。該函數(shù)返回一個矩陣:第一列是完整匹配,第二列及以后是每個分組(括號)的匹配。適用于啟發(fā)式的匹配提取,例如前綴、后綴等
str_match("bacad","b(a)") #提取前一個字符為b的a
str_match("bacad","[^b](a)") ##提取前一個字符不為b的a
#回溯引用
str_match("banana","(a)(.)(\\1\\2)") #提取aXaX的模式文本,其中X可以是任何文本
3、字符串的替換修改
str_replace()
?str_replace #默認(rèn)只替換第一個模式的文本
?str_replace_all #全部
fruits = c("apple","banana","pear")
str_replace(fruits, "[aeiou]", "-")
#回溯應(yīng)用,下面表示將a替換為aa,e替換為ee
str_replace(fruits, "([aeiou])", "\\1\\1")
#向量化一對一替換
str_replace(fruits, "[aeiou]", c("1", "2", "3"))
str_replace_all(fruits, "[aeiou]", c("1", "2", "3"))
str_replace(fruits, c("p", "e", "a"), "-")
str_replace_all(fruits, c("p", "e", "a"), "-")
# 多種特定模式的替換,僅限于str_replace_all
fruits %>%
str_c(collapse = "---") %>%
str_replace_all(c("one" = "1", "two" = "2", "three" = "3"))
4、字符串格式相關(guān)
- 4.1
str_length():返回每個字符串的長度
str_length(c("i", "like", "programming", NA))
- 4.2
str_pad():將字符串填補(bǔ)至指定長度,默認(rèn)用空格填充
rbind(
str_pad("hadley", 30, "left"),
str_pad("hadley", 30, "right"),
str_pad("hadley", 30, "both")
)
str_pad("a", 10, pad = c("-", "_", " "))
- 4.3
str_trunc():限制字符串的長度,用省略號代替
x <- "This string is moderately long"
rbind(
str_trunc(x, 20, "right"),
str_trunc(x, 20, "left"),
str_trunc(x, 20, "center")
)
- 4.4
str_trim():去除字符串兩邊的空格(包括tab、換行符);
str_squish():去除字符串兩邊的空格(tab、換行符),以及替換所有兩個以上的空格為一個空格
str_trim(" String with trailing and leading white space\t")
str_trim("\n\nString with trailing and leading white space\n\n")
str_squish(" String with trailing, middle, and leading white space\t")
- 4.5
str_wrap():將太長的英語句子限制為每行僅包含指定長度字符的若干行文本(本質(zhì)上即為自動插入換行符);首要前提需要為包含空格的字符串
sentences[1]
cat(str_wrap(sentences[1],width = 10))
- 4.6
str_glue():使用占位符格式化輸出,類似于sprintf()
name <- "Fred"
age <- 50
str_glue("My name is {name}, my age next year is {age + 1}")
mtcars[1:3,] %>% str_glue_data("{rownames(.)} has {hp} hp")
- 4.7 大小寫轉(zhuǎn)換
dog <- "The quick brown dog"
##變大寫
str_to_upper(dog)
##變小寫
str_to_lower(dog)
##首字母大寫
str_to_title(dog)
5、字符串拼接與拆分
-
str_c():拼接兩個字符串,默認(rèn)連接符為空白
str_c("Letter-", letters)
str_c("Letter", letters, sep = ": ")
str_c(letters, collapse = "")
-
str_dup()重復(fù)字符串`
fruit <- c("apple", "pear", "banana")
str_dup(fruit, 2)
str_dup(fruit, 1:3)
-
str_split()拆分字符串,默認(rèn)返回的是list,可設(shè)置simplify=T參數(shù)返回矩陣
fruits <- c(
"apples and oranges and pears and bananas",
"pineapples and mangos and guavas"
)
str_split(fruits, " and ")
str_split(fruits, " and ", simplify=T)
#限定分割得到的字符串的數(shù)量(從左到右)
str_split(fruits, " and ", n = 2)
str_split(fruits, " and ", n = 3)
str_split(fruits, " and ", n = 5)

