所有这些看起来非常相似的功能之间有什么区别?
答案 0 :(得分:7)
stri_join
,stri_c
和stri_paste
来自程序包 stringi
,它们是纯别名
str_c
来自 stringr
,只是stringi::stri_join
,其参数ignore_null
硬编码为TRUE
,而{ {1}}的默认设置为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>
与stri_join
非常相似,下面列举了一些区别:
1。 base::paste
默认情况下
因此,默认情况下,它的行为更像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
的行为与此处的str_c
一样。
2。 stri_join
如果使用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
的行为也将与str_c
一样
3。具有长度stri_join
个参数的行为
遇到长度为0的值时,将返回0
,除非将character(0)
设置为ignore_null
,则将忽略该值。它与FALSE
的行为不同,后者的行为是将长度paste
的值转换为0
,因此在输出中包含2个连续的分隔符。
""
4。 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"
警告更多
stri_join
5。 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
更快
stri_join