1 Goal


The goal of this tutorial is to learn how to create strings pasting information from different variables. This process can be useful when we need to create a filename from variables or using the index of a loop.


2 The paste function


# We can create sentences by pasting individual words
paste("You", "shall", "not", "pass")
## [1] "You shall not pass"
# However it's not always useful to add spaces between words
# Let's see how to create a date
paste(format(Sys.Date(),"%d"), format(Sys.Date(),"%m"), format(Sys.Date(),"%Y") )
## [1] "10 11 2017"
# Now we introduce - as separator
paste(format(Sys.Date(),"%d"), format(Sys.Date(),"%m"), format(Sys.Date(),"%Y"), sep = "-" )
## [1] "10-11-2017"
# Or /
paste(format(Sys.Date(),"%d"), format(Sys.Date(),"%m"), format(Sys.Date(),"%Y"), sep = "/" )
## [1] "10/11/2017"
# We can paste a character to each element of a vector
my_vector <- LETTERS  
my_vector
##  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q"
## [18] "R" "S" "T" "U" "V" "W" "X" "Y" "Z"
paste(LETTERS, "1")
##  [1] "A 1" "B 1" "C 1" "D 1" "E 1" "F 1" "G 1" "H 1" "I 1" "J 1" "K 1"
## [12] "L 1" "M 1" "N 1" "O 1" "P 1" "Q 1" "R 1" "S 1" "T 1" "U 1" "V 1"
## [23] "W 1" "X 1" "Y 1" "Z 1"
# Or collapse all letters together
paste(LETTERS, collapse = "")
## [1] "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# If we want to crate a single string from a vector of words
loftr <- c("You", "shall", "not", "pass")
paste(loftr, collapse = " ")
## [1] "You shall not pass"

3 Paste0


# Paste0 is just a quick way to append strings without separation
paste0("You", "shall", "not", "pass")
## [1] "Youshallnotpass"
# paste0 is equivalent to paste( , sep="")
paste("You", "shall", "not", "pass", sep = "")
## [1] "Youshallnotpass"
# This function is very useful when creating filenames
paste0(paste(format(Sys.Date(),"%Y"), format(Sys.Date(),"%m"), format(Sys.Date(),"%d"), sep = "_" ), ".csv")
## [1] "2017_11_10.csv"

4 Sprintf


# Sprintf is different from the other options
# Rather than pasting elements we create a single string where elements are introduced
my_day <- format(Sys.Date(),"%d")
my_month <- format(Sys.Date(),"%m")
my_year <- format(Sys.Date(),"%Y")

sprintf("%s-%s-%s.csv",my_year, my_month, my_day)
## [1] "2017-11-10.csv"
# We use %s to mark the position of the variables that we are going to append 

# The same example using paste would be
paste0(paste(my_year, my_month, my_day, sep = "-"),".csv")
## [1] "2017-11-10.csv"

5 Conclusion


In this tutorial we have learnt how to create new strings pasting different strings, vector or variables. We have used this examples to create filenames or combine a vector of strings into a single string.