nchar
取字符数量的函数
length与nchar不同,length是取向量的长度
# nchar表示字符串中的字符的个数
nchar("abcd")
[1] 4
# length表示向量中元素的个数
length("abcd")
[1] 1
length(c("hello", "world"))
[1] 2
paste
字符串粘合函数
paste在不指定分割符的情况下,默认分割符是空格
paste0在不指定分割符的情况下,默认分割符是空
# 默认以空格隔开
paste("Hello","world")
[1] "Hello world"
# 没有空格
paste0("Hello","world")
[1] "Helloworld"
# 指定分割符
paste("abc", "efg", "hijk", sep = "-")
[1] "abc-efg-hijk"
# 分别对向量的每一个元素进行连接
paste0("A", 1:6, sep = "")
[1] "A1" "A2" "A3" "A4" "A5" "A6"
# collapse参数:每一个元素操作之后,在把向量的每一个元素进行连接
paste0("A", 1:6, sep = "",collapse = "-")
[1] "A1-A2-A3-A4-A5-A6"
substr
字符串截取函数
substr(x = "hello", start = 1, stop = 2)
[1] "he"
strsplit
字符串的分割函数,可以指定分割符,生成一个list
strsplit("abc", split = "")
[[1]]
[1] "a" "b" "c"
如果要对一个向量使用该函数,需要注意。
# 分割向量的每一个元素,并取分割后的第一个元素
unlist(lapply(X = c("abc", "bcd", "dfafadf"), FUN = function(x) {return(strsplit(x, split = "")[[1]][1])}))
[1] "a" "b" "d"
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"
grep和grepl
字符串匹配
grep函数返回的是索引值
grepl函数返回的是逻辑值
# 返回匹配到的元素的索引
grep(pattern = "boy", x = c("abcb", "boy", "baby"))
[1] 2
# 返回逻辑值
grepl(pattern = "boy", x = c("abcb", "boy", "baby"))
[1] FALSE TRUE FALSE
时间: 2024-10-25 08:28:58