R 字符串操作超全总结
阅读原文时间:2023年07月08日阅读:6
  • paste函数和paste0()函数 连接字符

    paste("a", 1:3) #默认空格符连接,即sep=" "
    [1] "a 1" "a 2" "a 3"
    paste("a",1:3, sep = "") #a自动与每个元素连接
    [1] "a1" "a2" "a3"
    paste("a",1:4,".csv", sep = "") #批量输出文件名
    [1] "a1.csv" "a2.csv" "a3.csv" "a4.csv"
    #sep连接的是元素间的扩展,collapse是一种元素间的折叠坍缩
    paste("a", 1:3, sep = "", collapse = "+")
    [1] "a1+a2+a3"
    paste(c("a","b"), 1:5, sep = "") #超出范围后继续从前向后连接
    [1] "a1" "b2" "a3" "b4" "a5"
    paste0(c("a","b"), 1:5) #默认不加空格sep=""连接,这是与paste()函数的唯一不同
    [1] "a1" "b2" "a3" "b4" "a5"
    #下列命令可将barcode列的字符后都加上“-1”
    predict_result$barcode <- paste(predict_result$barcode,"-1", sep = "")

  • substr/substring 提取或替换字符串向量中的字符

substr(x, start, stop)
substring(text, first, last = 1000000L)
substr(x, start, stop) <- value
substring(text, first, last = 1000000L) <- value
注:x/text:字符向量;start/first:整数,要替换的第一个元素;stop/last:要替换的最后一个元素;value:字符向量

> substr(rep("abcdef", 4), 1:4, 4:5)
[1] "abcd" "bcde" "cd"   "de"
> x <- c("asfef", "qwerty", "yuiop[", "b", "stuff.blah.yech")
> substr(x, 2, 5)
[1] "sfef" "wert" "uiop" ""     "tuff"
> substring(x, 2, 4:6)
[1] "sfe"   "wert"  "uiop[" ""      "tuff"
> substr(x, 1, 3) <- c("aaa", "bcd", "s","ee")#替换
> x
[1] "aaaef"           "bcdrty"          "suiop["          "e"
[5] "aaaff.blah.yech"
  • nchar(x) 计算字符串长度

    x <- c("asfef", "qwerty", "yuiop[", "b", "stuff.blah.yech")
    nchar(x) #计算字符串长度
    [1] 5 6 6 1 15

  • chartr()转化字符串向量中的字符串

    a <- c("aBcdEf","1234","AbwSxT")
    chartr("abS","WHY",a) #注意在转换的过程中区分大小写
    [1] "WBcdEf" "1234" "AHwYxT"

  • tolower(x)和toupper(x) 字符串大小写转换函数

    a <- c("aBcdEf","1234","AbwSxT")
    tolower(a) #将大写字母转换成小写
    [1] "abcdef" "1234" "abwsxt"
    toupper(a) #将小写字母转换成大写
    [1] "ABCDEF" "1234" "ABWSXT"
    casefold(a, upper = FALSE)
    [1] "abcdef" "1234" "abwsxt"
    casefold(a, upper = TRUE)
    [1] "ABCDEF" "1234" "ABWSXT"

  • stringr包

按照特定的字符拆分字符串:str_split
str_split(string, pattern, n = Inf, simplify = FALSE)
str_split_fixed(string, pattern, n)
str_locate() 返回首个匹配模式的字符的位置
str_locate_all() 返回所有匹配模式的字符的位置

> library(stringr)
> hw <- "IGHV3-30*18, IGHV3-30-5*01"
> a <- str_split(hw, ",")#默认输出结果是一个列表
> class(a)
[1] "list"
> b <- str_split(hw, ",", simplify = TRUE) #当参数simplify=T时,输出结果是矩阵
> b
     [,1]          [,2]
[1,] "IGHV3-30*18" " IGHV3-30-5*01"
> ##提取字符串中的特定字符
> c <- str_sub(b[,1],1, str_locate(b[,1], "\\*")[1]-1)
> c
[1] "IGHV3-30"

> #"."表示除了换行符以外的任一字符。将1.2以“.”分割开需要用到[.]
> d <- c("bcfe","12.333")
> str_split(d, "[.]", simplify = TRUE)
     [,1]   [,2]
[1,] "bcfe" ""
[2,] "12"   "333"