Using the command paste
in R, I wanted to use both arguments sep
and collapse
, but you cannot abbreviate collapse
to coll
or even collaps
. Yet for other functions partial abbreviation works.
For example:
paste(letters, colla=", ")
# [1] "a , " "b , " "c , " "d , " "e , " "f , " "g , " "h , " "i , " "j , " "k , " "l , " "m , " "n , " "o , " "p , " "q , " "r , "
[19] "s , " "t , " "u , " "v , " "w , " "x , " "y , " "z , "
paste(letters, collapse=", ")
# [1] "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z"
There are no other arguments to collapse that start with coll
, which would interfere with the partial argument matching.
Why must I type out the entire argument name when calling paste
, when I do not have to for other functions?
I believe it's the ...
in paste that causes that you have to use exact argument matching. Specifically, the fact that ,collapse
comes after the ...
in the argument list.
Demonstration:
f1 <- function(x, collapse) cat("collapse",collapse)
f2 <- function(..., collapse) cat("collapse",collapse)
f3 <- function(collapse, ...) cat("collapse",collapse)
> f1(c="test",1)
collapse test
> f2(1,c="test")
Error in base::cat(...) : argument "collapse" is missing, with no default
> f2(1,collapse="test")
collapse test
> f3(c="test",1)
collapse test
A wrapper function might be helpful, much like paste0
p <- function(..., s=" ", clap=NULL) { # or whichever abbreviation you prefer. I originally had `col`, but that was dumb.
paste(..., sep=s, collapse=clap)
}
p0 <- function(..., clap=NULL) {
paste(..., sep="", collapse=clap)
}
eg :
p(c("hello", "world"), c("abc", "123"), clap="$")
# [1] "hello abc$world 123"
p0(c("hello", "world"), c("abc", "123"), clap="$")
# [1] "helloabc$world123"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With