r语言clind函数_R语言学习:paste/paste0函数讲解
该R包提供了灵活处理各种字符串操作的能力,并且在R中还有paste及paste0函数等工具可用于方便地连接多个字符串。
函数用法:
paste (..., sep = " ", collapse = NULL)
paste0(..., collapse = NULL)
paste0默认sep=””,这是两个函数唯一的区别
paste0(1:12)paste(1:12)as.character(1:12)
多个向量一一对应的连接
paste0(1:12, c("st", "nd", "rd", rep("th", 9)))
设置分隔符
paste("a","b","c",sep = "+")
collapse参数可以使元素连接后合并在一起成为一个元素
paste0(1:12, c("st", "nd", "rd", rep("th", 9)))paste0(1:12, c("st", "nd", "rd", rep("th", 9)),collapse = "+")
再来回顾一下stringr包
str_c连接字符串
library(stringr)str_c("x", "y","z")str_c("x", "y", sep =", ")
str_length计算字符串长度
x [1] 3 5 5 5 4 9
str_sub取子集
str_sub(x, 1, 2)#> [1] "wh" "vi" "cr" "ex" "de" "au"str_sub(x, 1, 3)#> [1] "why" "vid" "cro" "ext" "dea" "aut"
str_split函数进行拆分
fruits
默认返回的是列表
可以使用unlist()
unlist(str_split(fruits, " and "))
使用simplify = TRUE返回矩阵
str_split(fruits, " and ", simplify = TRUE)
使用 n= 可以限制拆分个数
str_split(fruits, " and ", n = 3)str_split(fruits, " and ", n = 2)
使用str_split_fixed也可以返回矩阵
str_split_fixed(fruits, " and ", 3)str_split_fixed(fruits, " and ", 4)
str_order(),str_sort()对字符向量排序
Returns the sorted indices of the input vector> str_order(x, decreasing = FALSE, na_last = TRUE, locale = "", ...)## Returns the sorted actual values of the input vector> str_sort(x, decreasing = FALSE, na_last = TRUE, locale = "", ....)# decreasing: specifies the sort order (default: ascending)# na_last: whether missing values are placed last (default: TRUE)
str_order(letters)str_sort(letters)
排序法则,默认是locale = “en”
string ordering operation on the letters with the language locale set to 'en'; similarly, a string sorting procedure is performed for the letters using a language locale of 'haw'.
str_replace字符串替换
函数 str\_replace 与 str\_replace\_all 均接受三个参数:目标字符序列、搜索模板以及目标新字符串 . 其中 string 表示需处理的目标字符序列 . 其中 pattern 定义了要搜索的模板字符串 . 其中 replacement 则指定了新生成的目标新字符串 . 在具体应用中,默认情况下两者的主要区别体现在执行方式上:即 str\_replace 仅执行单次替换操作;而 str\_replace\_all 则可一次性完成全部符合模板的所有对象替代
fruits
str_replace(fruits, "[aeiou]", c("1", "2", "3"))str_replace(fruits, c("a", "e", "i"), "-")
下回见。
