本文來源于陳興棟弊知、張鐵軍阻逮、劉振球老師編寫的《R語言與數據清洗》第11章字符串的操作學習筆記。
1. 字符串的長度
length():統(tǒng)計字符串的長度秩彤,一個引號之內屬于一個字符串叔扼;
nchar():統(tǒng)計字符串之內的字符數
x <- "R"
y <- "I love R"
length(x)
## [1] 1
length(y)
## [1] 1
my_string <- "I love China"
nchar(my_string)
##[1] 12
注意:一個向量之中,只要包含一個字符串漫雷,即使其余元素不是字符串瓜富,也會轉變?yōu)樽址6址滞蔀橐蜃幼兞拷淀铩与柑?梢酝ㄟ^以下修改:options(stringsAsFactors = FALSE) #禁止chr轉成factor
2. 字符串的粘貼與拆分
paste():參數:sep默認為空格,可以自己調整蓄坏;
參數:collapse价捧, 用來將所有返回的結果合并成一個完整而獨立的字符串。默認取值NULL剑辫,即不進行合并干旧。、
paste0():無縫粘貼妹蔽。
strsplit():字符串的分割函數椎眯,可以指定分割符挠将,生成一個list
a <- letters[1:4]
b <- 1:4
paste(a,b,sep = "-",collapse = ";")
## [1] "a-1;b-2;c-3;d-4"
a <- "I love"
b <- "China"
paste0(a,b)
## "I loveChina"
my_string2 <- "I love China"
strsplit(my_string2,split = " ")
## [[1]]
## [1] "I" "love" "China"
my_string3 <- "R is a program;R is proficient at data science;R is excellent in data visualization"
strsplit(my_string3,split = ";")
## [[1]]
## [1] "R is a program" "R is proficient at data science" "R is excellent in data visualization"
x <- "AppleBoyCatDogEggZoo"
strsplit(x,split = '[A-Z]')
## [[1]]
## [1] "" "pple" "oy" "at" "og" "gg" "oo"
y <- "Apple!Boy#Cat@Dog%Egg&Zoo"
strsplit(y,split = "\\W")
## [[1]]
## [1] "Apple" "Boy" "Cat" "Dog" "Egg" "Zoo"
3. 字符串提取
substr():參數start, stop
substring()參數first, last
另外,這兩個函數還有賦值替換功能编整。
substr("abcdef",start = 1, stop = 3)
substring("abcdef",first = 1, last = 3)
x <- c("Barcelona","Real Madrid","Arsenal","Chelsea")
substr(x,1,3:6)
substr(x,1,3) <- "+++"
#x的第一位到第三位字符被替換為“+++”舔稀;
substr(x,1,1) <- "<<<"
#雖然“<<<”有三個字符,但是由于我們指定的替換位置只有一個字符長度掌测,因此内贮,僅有第一個字符被替換成“<”
4. gsub和sub
字符串替換
gsub替換匹配到的全部
sub 替換匹配到的第一個
# 將b替換為B
gsub(pattern = "b", replacement = "B", x = "baby")
[1] "BaBy"
gsub(pattern = "b", replacement = "B", x = c("abcb", "boy", "baby"))
[1] "aBcB" "Boy" "BaBy"
# 只替換第一個b
sub(pattern = "b", replacement = "B", x = "baby")
[1] "Baby"
sub(pattern = "b", replacement = "B", x = c("abcb", "baby"))
[1] "aBcb" "Baby"
5.grep和grepl
字符串匹配
grep函數返回的是索引值
grepl函數返回的是邏輯值
seq_names <- c('EU_FRA02_C1_S2008','AF_COM12_B0_2004','AF_COM17_F0_S2008','AS_CHN11_C3_2004',
'EU-FRA-C3-S2007','NAUSA02E02005', 'AS_CHN12_N0_05','NA_USA03_C2_S2007','NA USA04 A3 2004',
'EU_UK01_A0_2009','eu_fra_a2_s98', 'SA/BRA08/B0/1996')
fra_seq <- grep(pattern = 'FRA|fra', x = seq_names)
fra_seq
seq_names[fra_seq]
grep(pattern = 'FRA|fra', x = seq_names, value = TRUE)
grepl(pattern = 'FRA|fra', x = seq_names)
seq_names[grepl(pattern = 'FRA|fra', x = seq_names)]
spe_seq <- seq_names[which(! grepl('[s|S][0-9]{2,4}\\b', seq_names))]
#[]表示具體的匹配對象
#{}表示前面的表達式重復的次數
#\\b,b是“boundary"的縮寫汞斧,限制字符的邊界夜郁,\\b放在開頭,則正則表達式應用于開頭粘勒;\\b放在末尾竞端,則正則表達式應用于末尾
spe_seq
a_seq <- grep('[a|A][0-9]{1}', seq_names, value = TRUE)
a_seq
a_seq02 <- grep('^[A-Za-z]{2}.[A-Za-z]{2,3}.[0-9]{0,2}.[aA]',seq_names,value = TRUE)
a_seq02
6. regexpr()函數
匹配的具體位置和字符串長度
test_string <- c('happy', 'apple','application','apolitic','noppppy')
regexpr('pp',test_string)
## [1] 3 2 2 -1 3
attr(,"match.length")
## [1] 2 2 2 -1 2
attr(,"index.type")
### [1] "chars"
attr(,"useBytes")
### [1] TRUE
7. gregexpr和regexex函數
gregexpr(pattern,text)函數可以在字符串x中提取出特定字符串pattern的相關信息,返回第一次的匹配結果(原文)庙睡,但是根據下面的結果來說不是這樣的事富,原因以后探索。
regexex(pattern,text)函數可以在字符串x中提取出特定字符串pattern的相關信息乘陪,返回所有匹配到的結果
兩者都是以列表的形式返回結果统台。
test_string <- c('happy', 'apple','application','apolitic','noppppy')
gregexpr('pp',test_string)
[[1]]
[1] 3
attr(,"match.length")
[1] 2
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
[[2]]
[1] 2
attr(,"match.length")
[1] 2
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
[[3]]
[1] 2
attr(,"match.length")
[1] 2
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
[[4]]
[1] -1
attr(,"match.length")
[1] -1
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
[[5]]
[1] 3 5
attr(,"match.length")
[1] 2 2
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
> regexec('pp',test_string)
[[1]]
[1] 3
attr(,"match.length")
[1] 2
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
[[2]]
[1] 2
attr(,"match.length")
[1] 2
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
[[3]]
[1] 2
attr(,"match.length")
[1] 2
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
[[4]]
[1] -1
attr(,"match.length")
[1] -1
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
[[5]]
[1] 3
attr(,"match.length")
[1] 2
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
8. agrep()函數
允許通假字的存在,這個比喻形象啡邑。
test_string4 <- c('I need a favor', 'my favouriate book','you made a favouur')
agrep('favor',test_string4, max.distance = 1) #max.distance 改變最大匹配距離
##[1] 1 2 3
9. 大小寫替換函數:toupper()贱勃、tolower()、casefold()
toupper()函數:將字符串統(tǒng)一轉換為大寫谣拣。
tolower()函數:將字符串統(tǒng)一轉換為小寫募寨。
casefold()函數:根據參數轉換大小寫。
chartr (old,new,x)森缠,chartr-將對象中舊的字符用新的字符替代拔鹰。其中參數old 表示原有字符串中內容;new 表示替換后的字符內容贵涵。
??tolower(x)
??toupper(x)
??casefold(x, upper = FALSE)
??chartr(old, new, x)
### 這兩個函數就不用多介紹了列肢,按字面意思就是把對象轉換成大寫或小寫,應用于全部的對象宾茂,例如:
toupper("abc")
##[1]"ABC"
tolower("ABC")
##[1]"abc"
x<-c("My","First","Trip")
tolower(x)
## [1] "my" "first" "trip"
casefold('ABDATA', upper = FALSE)
##[1] "abdata"
casefold('baorui', upper = FALSE)
## [1] "baorui"
casefold('baorui', upper = TRUE)
## [1] "BAORUI"
# 這里這只提供全部應用的大小寫轉換瓷马,部分轉換可以參照函數chartr()。
chartr(old, new, x)
10. match 匹配元素位置組成的向量
match按向量進行運算跨晴,返回第一次匹配的元素的位置(如果有)欧聘,非字符向量也可用。
match("xx", c("abc", "xx", "xxx", "xx"))
## [1] 2
參考:陳興棟端盆、張鐵軍怀骤、劉振球老師《R語言與數據清洗》
生信技能樹公益視頻合輯:學習順序是linux费封,r,軟件安裝蒋伦,geo弓摘,小技巧,ngs組學痕届!
B站鏈接
YouTube鏈接
生信工程師入門最佳指南
學徒培養(yǎng)