[R] sum the values in a vector as a complete number

Petr PIKAL petr.pikal at precheza.cz
Wed Feb 2 11:45:54 CET 2011


Hi


r-help-bounces at r-project.org napsal dne 01.02.2011 07:02:50:

> Hi AD,
> 
> You might try the following:
> 
> # data
> a <- c(2,3,5)
> b <- c(8,7)   # you got this wrong ;)
> 
> # option 1
> foo <- function(x) as.numeric(paste(x, sep = "", collapse = ""))
> 
> # examples
> foo(a)
> # [1] 235
> foo(b)
> # [1] 87
> foo(a) + foo(b)
> # [1] 322
> 
> # option 2
> foo2 <- function(x, y) foo(x) + foo(y)
> 
> # example
> foo2(a, b)
> # [1] 322
> 
> See ?paste and ?as.numeric for more information.
> 
> HTH,
> Jorge

Above solutions are maybe quicker but here is one plain numeric.

fff<-function(x) rev(10^(0:(length(x)-1)))
sum(a*fff(a))+sum(b*fff(b))
[1] 322

or you can put the whole operation inside a function

fff<-function(x) sum(x*rev(10^(0:(length(x)-1))))
fff(a)+fff(b)

Regards
Petr



> 
> On Mon, Jan 31, 2011 at 11:22 PM, ADias <> wrote:
> 
> >
> > Hi
> >
> > I am trying to create a function that is able to calculate this sum:
> >
> > a<-c(2,3,5)
> > b<-(8,7)
> >
> > with "a" meaning 235 and "b" 87. So the result of this sum would be 
235 +
> > 87
> > = 322.
> >
> > I've searched a function like strsplit but that worked for integers 
and in
> > reverse - not spliting but combining.
> >
> > Can you give me a hand on this please?
> >
> > thanks
> > AD
> > --
> > View this message in context:
> > 
http://r.789695.n4.nabble.com/sum-the-values-in-a-vector-as-a-complete-
> number-tp3250470p3250470.html
> > Sent from the R help mailing list archive at Nabble.com.
> >
> > ______________________________________________
> > R-help at r-project.org mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide
> > http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> >
> 
>    [[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list