Search notes:
R functions: paste / paste0
paste
concatenates strings.
paste("foo", "bar", "baz")
# "foo bar baz"
sep
When using paste
without the sep
argument, a space is put between the concatenated strings.
With the sep
argument, another string can be specified that is put between the joined strings.
paste("foo", "bar", "baz", sep=" - ")
# [1] "foo - bar - baz"
paste vs paste0
While paste
uses a space to join strings, paste0
defaults sep
to the empty string.
That is paste0(…, collapse) is the equivalent of paste(,…, sep = "", collapse)
.
paste ("foo", "bar", "baz")
#
# "foo bar baz"
paste0("foo", "bar", "baz")
#
# "foobarbaz"
Vectors
When the first argument to
paste
is a
vector ,
paste
concatenates corresponding elements of all passed vectors.
Thus, another vector is returned:
paste( c('one', 'two', 'three' ),
c('A' , 'B' , 'C' )
);
# "one A" "two B" "three C"
Recyclation rule
If the number of the elements in the passed vectors differs, paste
uses the recyclation rule to concatenate the respective elements:
First case: the number of elements in all vectors are equal (=10):
paste(1:10, 101:110, letters[1:10], sep="-")
# [1] "1-101-a" "2-102-b" "3-103-c" "4-104-d" "5-105-e" "6-106-f"
# [7] "7-107-g" "8-108-h" "9-109-i" "10-110-j"
Second case: the number of elements in all vectors differ:
paste(c('A', 'B', 'C'), 1:7, sep="-")
# [1] "A-1" "B-2" "C-3" "A-4" "B-5" "C-6" "A-7"
Using collapse
When using the
collapse
argument, the returned vector us pasted a second time and the value of
collapse
is used to merge the elements of the elements in the vector. The behavior is then similar to
Perl's join
function .
paste(c('A', 'B', 'C'), 1:7, sep="-", collapse="/")
# [1] "A-1/B-2/C-3/A-4/B-5/C-6/A-7"