Why can't I combine Reduce with paste when using "*" as a character?

Viewed 187

I'm trying to get the output "1*2*4*5" from (function(x) Reduce(paste0(toString("*")),x))(c(1,2,4,5)), but no matter how I manipulate Reduce, paste0, and the asterisks, I'm either getting error messages or the asterisks being treated as multiplication (giving 40). Where am I going wrong?

3 Answers

Reduce uses a function with two arguments to which it applies the previous result and the next element of the vector. Therefore, you need a function of both x and y:

Reduce(function(x,y)paste0(x,"*",y),c(1,2,4,5))
#[1] "1*2*4*5"

As an aside, you can provide an initial value to be applied as x for the first element of the vector with init =.

Reduce(function(x,y)paste0(x,"*",y),c(1,2,4,5), init = 0)
#[1] "0*1*2*4*5"

One thing you may have tried was this:

Reduce(paste0("*"),c(1,2,4,5))
#[1] 40

This applies the multiplication operator to x and y, because paste0("*") evaluates to "*".

Another base R option is to use paste within gsub, e.g.,

x <- 1:5
gsub("\\s","*",Reduce(paste,x))

which gives

> gsub("\\s","*",Reduce(paste,x))
[1] "1*2*3*4*5"

KISS method:
(with improvements as suggested by @nicola)

bar <- as.character(1:5)
 paste0(bar,sep="",collapse='*')
#[1] "1*2*3*4*5"
Related