'What is the difference between paste/paste0 and str_c?
I don't seem to see a difference between paste/paste0 and str_c for combining a single vector into a single string, multiple strings into one string, or multiple vectors into a single string.
While I was writing the question I found this: https://www.rdocumentation.org/packages/stringr/versions/1.3.1/topics/str_c. The community example from [email protected] says the difference is is that str_c treats blanks as blanks (not as NAs) and recycles more appropriately. Any other differences?
Solution 1:[1]
paste0(..., collapse = NULL)is a wrapper for paste(..., sep = "", collapse = NULL), which means there is no separator. In other words, with paste0() you can not apply some sort of separator, while you do have that option with paste(), whereas a single space is the default.
str_c(..., sep = "", collapse = NULL) is equivalent to paste(), which means you do have the option to customize your desired separator. The difference is for str_c() the default is no separator, so it acts just like paste0() as a default.
Paste() and paste0() are both functions from the base package, whereas str_c() comes from the stringr package.
I did not test/microbenchmark it, but from my experience I do agree to Ryan str_c() is generally faster.
Solution 2:[2]
There are two key ways
str_c()differs frompaste(). First, the default separator is an empty string,sep = "", as opposed to a space, so it's more likepaste0(). This is an example of a stringr function, performing a similar operation to a base function, but using a default that is more likely to be what you want. {...}The second way
str_c()differs topaste()is in its handling of missing values.paste()turns missing values into the string"NA", whereasstr_c()propagates missing values. That means combining any strings with a missing value will result in another missing value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | vrognas |
