Created
November 27, 2014 07:11
-
-
Save briandk/d9231ba1e2603eed0df1 to your computer and use it in GitHub Desktop.
Understanding `sep` and `collapse` in R using `paste()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The difference between the `sep` and `collapse` arguments | |
# in paste can be thought of like this: | |
# | |
# paste can accept multiple *vectors* as input, and will | |
# concatenate the ith entries of each vector pairwise | |
# (or tuplewise), if it can. | |
# | |
# When you pass paste multiple vectors, sep defines what | |
# separates the entries in those tuple-wise concatenations. | |
# | |
# When you pass paste a *collapse* value, it will return | |
# any concatenated pairs as part of a single length-1 | |
# character vector, with the tuples separated by | |
# the string you passed to `collapse` | |
x <- c("a", "b", "c", "d") | |
y <- c("w", "x", "y", "z") | |
# The statement below will return | |
# "a%%w" "b%%x" "c%%y" "d%%z" | |
# A tuple of character concatenations, where within | |
# each tuple, the concatenations are separated by the sep | |
# argument | |
paste(x, y, sep="%%") | |
# The statement below this will return | |
# "a%%w,b%%x,c%%y,d%%z" | |
# It's the same tuple-wise concatenation as above, | |
# but this time there's the additional step of reducing | |
# the output to a vector of length one and shoving the | |
# collapse value between the entries. Note how in the output | |
# there are four instances of "%%", but only three of "," | |
paste(x, y, sep="%%", collapse=",") | |
# To confirm our conjecture, we can swap the sep and | |
# collapse arguments. The statement below will return | |
# "a,w%%b,x%%c,y%%d,z" | |
paste(x, y, sep=",", collapse="%%") | |
Thank you!
Thank you! very informative!
Nice explanation, to add further, try running this
length(paste(x,y,sep = "%%",collapse=","))
Output: 1 (Returns a single character)
and this
length(paste(x,y,sep = "%%"))
Output: 4 (Returns character with length 4)
@Anant-mishra1729, you may need to edit the second code without the "collapse" to give the expected result, for the sake of new R users length(paste(x,y,sep = "%%"))
aah thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!