所有这些看似非常相似的功能之间有什么区别?
stri_join,stri_c和stri_paste来自包装stringi,是纯粹的别名
str_c来自stringr和只是stringi::stri_join一个参数ignore_null硬编码TRUE,而stringi::stri_join有它设置为FALSE默认.stringr::str_join是一个弃用的别名str_c
看到:
library(stringi)
identical(stri_join, stri_c)
# [1] TRUE
identical(stri_join, stri_paste)
# [1] TRUE
library(stringr)
str_c
# function (..., sep = "", collapse = NULL)
# {
# stri_c(..., sep = sep, collapse = collapse, ignore_null = TRUE)
# }
# <environment: namespace:stringr>
Run Code Online (Sandbox Code Playgroud)
stri_joinbase::paste与下面列举的一些差异非常相似:
1. sep = ""默认情况下
所以它paste0在默认情况下表现得更像,但却paste0失去了它的sep论点.
identical(paste0("a","b") , stri_join("a","b"))
# [1] TRUE
identical(paste("a","b") , stri_join("a","b",sep=" "))
# [1] TRUE
identical(paste("a","b", sep="-"), stri_join("a","b", sep="-"))
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)
str_c会表现得像stri_join这里一样.
2.行为 NA
如果你粘贴到NA使用stri_join,结果是NA,paste转换NA为"NA"
paste0(c("a","b"),c("c",NA))
# [1] "ac" "bNA"
stri_join(c("a","b"),c("c",NA))
# [1] "ac" NA
Run Code Online (Sandbox Code Playgroud)
str_c也会像stri_join这里一样表现
3.具有长度0参数的行为
当遇到长度为0的值时,character(0)返回,除非ignore_null设置为FALSE,否则忽略该值.它不同于paste将长度0值转换为""并因此在输出中包含2个连续分隔符的行为.
stri_join("a",NULL, "b")
# [1] character(0)
stri_join("a",character(0), "b")
# [1] character(0)
paste0("a",NULL, "b")
# [1] "ab"
stri_join("a",NULL, "b", ignore_null = TRUE)
# [1] "ab"
str_c("a",NULL, "b")
# [1] "ab"
paste("a",NULL, "b") # produces double space!
# [1] "a b"
stri_join("a",NULL, "b", ignore_null = TRUE, sep = " ")
# [1] "a b"
str_c("a",NULL, "b", sep = " ")
# [1] "a b"
Run Code Online (Sandbox Code Playgroud)
4. stri_join提醒更多
paste(c("a","b"),c("c","d","e"))
# [1] "a c" "b d" "a e"
paste("a","b", sep = c(" ","-"))
# [1] "a b"
stri_join(c("a","b"),c("c","d","e"), sep = " ")
# [1] "a c" "b d" "a e"
# Warning message:
# In stri_join(c("a", "b"), c("c", "d", "e"), sep = " ") :
# longer object length is not a multiple of shorter object length
stri_join("a","b", sep = c(" ","-"))
# [1] "a b"
# Warning message:
# In stri_join("a", "b", sep = c(" ", "-")) :
# argument `sep` should be one character string; taking the first one
Run Code Online (Sandbox Code Playgroud)
5. stri_join更快
microbenchmark::microbenchmark(
stringi = stri_join(rep("a",1000000),rep("b",1000),"c",sep=" "),
base = paste(rep("a",1000000),rep("b",1000),"c")
)
# Unit: milliseconds
# expr min lq mean median uq max neval cld
# stringi 88.54199 93.4477 97.31161 95.17157 96.8879 131.9737 100 a
# base 166.01024 169.7189 178.31065 171.30910 176.3055 215.5982 100 b
Run Code Online (Sandbox Code Playgroud)