[R] Evaluating a function with another function

Gabor Grothendieck ggrothendieck at gmail.com
Fri Apr 7 01:07:41 CEST 2006

```I assume you want a list containing length(x) data frames, one per
list component.  If that's it try this:

test <- function(x = 1:4, s = 1:2, rangit = 0:11)
lapply(x, function(x) data.frame(rangit, y = x+s[1]+rangit, p=x+s[2]+rangit))
test() # test run

On 4/6/06, Guenther, Cameron <Cameron.Guenther at myfwc.com> wrote:
> Hello all,
> I hope someone can help me with this.
>
> I have function that calculates two values based on input data.  A
> simple example follows:
>
> test<-function(x,s,rangit=seq(0,10,1))
> {
> rangit<-rangit
> y<-vector()
> p<-vector()
> for(i in 0:length(rangit)){
> y[i]<-x+s[1]+rangit[i]
> p[i]<-x+s[2]+rangit[i]
> }
> return(data.frame(rangit,y,p))
> }
>
> And returns the following:
>
>   rangit  y  p
> 1       0  2  3
> 2       1  3  4
> 3       2  4  5
> 4       3  5  6
> 5       4  6  7
> 6       5  7  8
> 7       6  8  9
> 8       7  9 10
> 9       8 10 11
> 10      9 11 12
> 11     10 12 13
>
> Which is what I want.  The part I am having trouble with is that I want
> to write another function that will evaluate the previous function at
> multiple levels of x, where the levels of x may not always be the same
> length
>
> I have tried several options but so far have not been able to figure it
> out.
>
> I tried:
>
> testexp<-function(x,s,rangit){
>        out<-data.frame()
>        for (j in 1:length(x)){
>                out[j]<-test(x[j],s)
>        }
>        return(out)
> }
> Q2<-testexp(x=c(1:4),s=c(1,2))
>
> But that returns a warning with no values.  I have also tried various
> other methods with no success.
>
> Basically what I want the output to look like is
>
> Out[1]  Out[2]  Out[3]  Out[4]
> Rangit y p      rangit y p      rangit y p      rangit y p
> 0      2 3  0      3 4  0      4 5  0      5 6
> 1      3 4  1      4 5  1      5 6  1      6 7
> 2      4 5  2      5 6  2      6 7  2      7 8
> 3      . .  .      . .  .      . .  .      . .
> 4      . .  .      . .  .      . .  .      . .
> 5      . .  .      . .  .      . .  .      . .
> 6      . .  .      . .  .      . .  .      . .
> 7      . .  .      . .  .      . .  .      . .
> 8      . .  .      . .  .      . .  .      . .
> 9      . .  .      . .  .      . .  .      . .
> 10     . .  .      . .  .      . .  .      . .
>
>
>
> Cameron Guenther, Ph.D.
> Associate Research Scientist
> FWC/FWRI, Marine Fisheries Research
> 100 8th Avenue S.E.
> St. Petersburg, FL 33701
> (727)896-8626 Ext. 4305
> cameron.guenther at myfwc.com
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help