Difference between paste() and paste0()

[This article was first published on R – DATABIOMICS, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Probably, function paste is one of the most used function in R. The objective of this function is concatenate a series of strings.

# First example

paste("file", "number", "32")

[1] "file number 32"

# Second example

paste("file", "number", "32", sep = "_")

[1] "file_number_32"

The arguments of the function are:

args(paste)
function (..., sep = " ", collapse = NULL)

= The space to write the series of strings.

sep = The element which separates every term. It should be specified with character string format.

collapse = The element which separates every result. It should be specified with character string format and it is optional. i

We can see an example where both arguments works together:

# Third example (5 strings created)

paste(rep("file", 5), rep("number", 5), seq(1,5,1), sep = "_")

[1] "file_number_1" "file_number_2" "file_number_3" "file_number 4" "file_number_5"

# Fourth example (an unique string created)

paste(rep("file", 5), rep("number", 5), seq(1,5,1), sep = "_", collapse = ", ")

[1] "file_number_1, file_number_2, file_number_3, file_number_4, file_number_5"

As we can see in fourth example, if we specify a value in argument collapse, we obtain an unique string instead of five as in the previous example

The difference between paste() and paste0() is that the argument sep by default is ” ” (paste) and “” (paste0).

# Default value of sep with paste function
name_village <- paste("Ma", "con", "do")
name_village
[1] "Ma con do"

# Value of sep: ""
name_village <- paste("Ma", "con", "do", sep = "")
name_village
[1] "Macondo"

# Default value of sep with paste function
name_village <- paste0("Ma", "con", "do")
name_village
[1] "Macondo"

In conclusion, paste0() is faster than paste() if our objective is concatenate strings without spaces because we don’t have to  specify the argument sep. 

To leave a comment for the author, please follow the link and comment on their blog: R – DATABIOMICS.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)