NChar
A function that takes a number of characters
Length is different from nchar.
# nchar表示字符串中的字符的个数nchar("abcd")[1] 4# length表示向量中元素的个数length("abcd")[1] 1length(c("hello", "world"))[1] 2
Paste
String glue function
Paste the default delimiter is a space without specifying a separator
Paste0 The default delimiter is empty without specifying a separator
# Separated by a space by defaultPaste"Hello","World")[1]"Hello World"# no spacesPASTE0 ("Hello","World")[1]"Helloworld"# Specify a separatorPaste"ABC","EFG","Hijk", Sep ="-")[1]"Abc-efg-hijk"# Connect each element of a vector separatelyPASTE0 ("A",1:6, Sep ="")[1]"A1" "A2" "A3" "A4" "A5" "A6"# collapse Parameters: After each element operation, connect each element of the vectorPASTE0 ("A",1:6, Sep ="", collapse ="-")[1]"A1-a2-a3-a4-a5-a6"
Substr
String intercept function
"hello"1stop2)[1"he"
Strsplit
The split function of the string, you can specify the delimiter, generate a list
strsplit("abc""")[[1]][1"a""b""c"
If you want to use this function on a vector, you need to be aware of it.
# 分割向量的每一个元素,并取分割后的第一个元素unlist(lapply(X = c("abc""bcd""dfafadf"function(x) {return"")[[1]][1])}))[1"a""b""d"
Gsub and Sub
String substitution
gsub Replace all matches to
The sub replaces the first one that matches the
# Replace B with BGsub (pattern ="B", replacement ="B", x ="Baby")[1]"BaBy"Gsub (pattern ="B", replacement ="B", x = C ("ABCB","Boy.","Baby"))[1]"ABCB" "Boy." "BaBy"# Replace only the first BSub (pattern ="B", replacement ="B", x ="Baby")[1]"Baby"Sub (pattern ="B", replacement ="B", x = C ("ABCB","Baby"))[1]"ABCB" "Baby"
grep and Grepl
String match
the grep function returns the index value
The GREPL function returns a logical value
# 返回匹配到的元素的索引grep(pattern = "boy", x = c("abcb", "boy", "baby"))[1] 2# 返回逻辑值grepl(pattern = "boy", x = c("abcb", "boy", "baby"))[1] FALSE TRUE FALSE
R language--string processing function