1. 创建字符串
> str1 <- "hsy" #双引号、单引号都行
> str2 <- 'hsy'
> str3 <- c("\\","\"") #字符向量用来存储多个字符串;如何“转义”
> writeLines(str3) #呈现字符串本身
\
"
2. 求字符串长度
str_length(str3)
3. 组合字符串
> str_c("a","b","c")
[1] "abc"
> str_c("a","b","c",c("d1","d2")) #自动循环
[1] "abcd1" "abcd2"
> str_c("a","b","c",sep = ", ") #几个分散的字符(串)合并为一个字符串
[1] "a, b, c"
> str_c(c("a","b","c"),collapse = ", ") #字符向量的几个元素合并为一个字符串
[1] "a, b, c"
4. 取子串
> x <- c("huang","si","yuan")
> str_sub(x,1,3) #对于向量会自动循环各元素;起始终止位点都包括在内;范围超了也没事
[1] "hua" "si" "yua"
该函数还能用于赋值
> str_sub(x,1,1) <- str_to_upper(str_sub(x,1,1))
> x
[1] "Huang" "Si" "Yuan"
网友评论