Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

r

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?

like image 631
J. Mini Avatar asked Oct 29 '25 09:10

J. Mini


2 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 "*".

like image 181
Ian Campbell Avatar answered Nov 01 '25 00:11

Ian Campbell


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

bar <- as.character(1:5)
 paste0(bar,sep="",collapse='*')
#[1] "1*2*3*4*5"
like image 41
Carl Witthoft Avatar answered Nov 01 '25 00:11

Carl Witthoft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!