# Re: [R] recursively divide a value to get a sequence

From: Berwin A Turlach <berwin_at_maths.uwa.edu.au>
Date: Wed, 09 Jul 2008 19:42:34 +0800

G'day all,

On Wed, 09 Jul 2008 20:33:39 +1000
Jim Lemon <jim_at_bitwrit.com.au> wrote:

> On Wed, 2008-07-09 at 11:40 +0200, Anne-Marie Ternes wrote:
> > Hi,
> >
> > if given the value of, say, 15000, I would like to be able to divide
> > that value recursively by, say, 5, and to get a vector of a
> > determined length, say 9, the last value being (set to) zero- i.e.
> > like this:
> >
> > 15000 3000 600 120 24 4.8 0.96 0.192 0
> >
> > These are in fact concentration values from an experiment. For my
> > script, I get only the starting value (here 15000), and the factor
> > by which concentration is divided for each well, the last one
> > having, by definition, no antagonist at all.
> >
> > I have tried to use "seq", but it can "only" do positive or negative
> > increment. I didn't either find a way with "rep", "sweep" etc. These
> > function normally start from an existing vector, which is not the
> > case here, I have only got a single value to start with.
> >
> > I suppose I could do something "loopy", but I'm sure there is a
> > better way to do it.
> >
> Well, if you really want to do it recursively (and maybe loopy as
> well)
>
> recursivdiv<-function(x,denom,lendiv,firstpass=TRUE) {
> if(firstpass) lendiv<-lendiv-1
> if(lendiv > 1) {
> divvec<-c(x/denom,recursivdiv(x/denom,denom,lendiv-1,FALSE))
> cat(divvec,ndiv,"\n")
> }
> else divvec<-0
> if(firstpass) divvec<-c(x,divvec)
> return(divvec)
> }

Or, a bit more compactly:

recursivdiv <- function(x,denom,lendiv) {

if(lendiv > 1) {
divvec<-c(x, Recall(x/denom,denom,lendiv-1))     }
else divvec<-0
return(divvec)
}

which will continue to work if the function is renamed (say, rcd <- recursivdiv) due to the use of Recall()

Cheers,

Berwin

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. Received on Wed 09 Jul 2008 - 11:49:13 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 09 Jul 2008 - 12:31:08 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.