stringr-----str_c() paste()
主页:https://cran.r-project.org/web/packages/stringr/index.html
#安装stringr包 > install.packages('stringr') > library(stringr)
#stringr函数分类:
字符串拼接函数
字符串计算函数
字符串匹配函数
字符串变换函数
参数控制函数
#stringr字符串拼接函数
~str_c
str_c(..., #多参数的输入
sep = "", #sep: 把多个字符串拼接为一个大的字符串,用于字符串的分割符
collapse = NULL #把多个向量参数拼接为一个大的字符串,用于字符串的分割符)
str_join(..., sep = "", collapse = NULL)
#把多个字符串拼接为一个大的字符串
> str_c('a','b') [1] "ab" > str_c('a','b',sep='-') [1] "a-b" > str_c(c('a','a1'),c('b','b1'),sep='-')
[1] "a-b" "a1-b1"
#把多个向量参数拼接为一个大的字符串
> str_c(head(letters), collapse = "") [1] "abcdef" > str_c(head(letters), collapse = ", ") [1] "a, b, c, d, e, f" # collapse参数,对多个字符串无效 > str_c('a','b',collapse = "-") [1] "ab" > str_c(c('a','a1'),c('b','b1'),collapse='-') [1] "ab-a1b1" # 如果是向量之间的连接,collapse的作用与sep一样,只不过此时sep无效 > str_c(c(1989,07,17), sep = '-') #使用sep [1] "1989" "7" "17" > str_c(c(1989,07,17), collapse = '-') #使用collapse [1] "1989-7-17" > str_c('x', c(1:10), ':') [1] "x1:" "x2:" "x3:" "x4:" "x5:" [6] "x6:" "x7:" "x8:" "x9:" "x10:"
#拼接有NA值的字符串向量时,NA还是NA
> str_c(c("a", NA, "b"), "-d") [1] "a-d" NA "b-d"
#对比str_c()函数和paste()函数之间的不同点
# 多字符串拼接,默认的sep参数行为不一致 > str_c('a','b') [1] "ab" > paste('a','b') [1] "a b" # 向量拼接字符串,collapse参数的行为一致 > str_c(head(letters), collapse = "") [1] "abcdef" > paste(head(letters), collapse = "") [1] "abcdef" #拼接有NA值的字符串向量,对NA的处理行为不一致 > str_c(c("a", NA, "b"), "-d") [1] "a-d" NA "b-d" > paste(c("a", NA, "b"), "-d") [1] "a -d" "NA -d" "b -d"