[R] Passing arguments to a function within a function ...

2012-08-07 Thread christiaan pauw
Hallo Everybody

How do you specify arguments for a function used within another function?

Here is my problem:

I am reconstructing a calculator for the burden of disease due to air
pollution from publications and tools published by the WHO. The
calculations make use of published dose-response relationships for
particular health end-points. This is then applied to populations with
known or estimated levels of exposure and incidence rates to calcute
the number of cases of each end-point attributable to each pollutant.
I have functions that work on their own but when is have to use the
one within the other, I don't know how to specify its arguments

Here are example data and the functions:


## Example data frame with population, concentration and cases ##

x = data.frame(Name = LETTERS[1:10],
   pop=sample(x=1000:1,size=10),
   Xbabies = 0.106,
   Xkids = 0.232,
   Xteens = 0.375,
   Xadults = 0.235,
   Xaged = 0.52,
   cases = sample(x=100:500,size=10),
   conc = sample(x=20:125,size=10)
   )

## Two of the published dose-response relationships

adult.CP.mortality = list(end.point = Cardiopulmanory mortality in
adults over 30,
  pollutant = PM10,
  relationship = log-linear,
  beta = c(0.0562,0.1551,0.2541),
  Xpop =
c(Xbabies,Xkids,Xteens,Xadults,Xaged)[4:5])

adult.LC.mortality = list(end.point = Lung Cancer mortality in adults over 30,
  pollutant = PM10,
  relationship = log-linear,
  beta = c(0.0856, 0.2322,0.3787),
  Xpop =
c(Xbabies,Xkids,Xteens,Xadults,Xaged)[4:5])

## Generic function to calculculate the Attributable cases for a
pollutant in a population
dose.response - function(pop,
  Xpop = 1,
  conc,
  base.conc=7.5,
  relationship = c(linear,log-linear)[1],
  beta=c(0.0006,0.0008,0.0010),
  cases=NULL,
  incidence.rate=NULL,
  par = c(low estimate,cental
estimate,high estimate),
  verbose = FALSE
  ){
  # Turn case rate into case number
  d - cases
  if(verbose==TRUE) message(d = , d)
  if(verbose==TRUE) message(pop = , pop)
  if(verbose==TRUE) message(beta = , beta)
  if(verbose==TRUE) message(conc = , conc)
  if(verbose==TRUE) message(base.coc = , base.conc)
  if(verbose==TRUE) message(relationship = , relationship)
  if(is.null(cases)==TRUE) {d - incidence.rate*pop} # use incidence
rate if cases are not available
  if(relationship == linear) {RR = exp(beta*(conc-base.conc))}
#RR=exp[beta(X-Xo)]
  if(relationship == log-linear) {RR = ((conc+1)/(base.conc+1))^beta}
  if(verbose==TRUE) message(RR = , RR)
  AF =  (RR-1)/RR  #AF=(RR-1)/RR
  if(verbose==TRUE) message(AF = , AF)
  AM =  AF * d #AM = AF * cases
  if(verbose==TRUE) message(AM = , AM)
  out = data.frame(beta=beta,cases=d,
   RelativeRisk=RR,AttributableFraction=AF,
   AttributableInsidence=AM)
  rownames(out) = c(low estimate,cental estimate,high estimate)
  if(verbose==TRUE) message(dimentions of out  = , dim(out))
  out.idx = na.omit(match(par,rownames(out)))
  out[out.idx,]
}

## Function using the  published dose-response relationships with the
generic function
drep - function(pop.conc=x,sicklist=adult.CP.mortality,...){
  dr.out=by(x,x$Name,function(x){z=as.data.frame((x))

dose.response(pop=z$pop*sum(z[,adult.CP.mortality$Xpop]),
  conc=z$conc,
  cases=z$cases,
  relationship =
sicklist$relationship,
  beta = sicklist$beta,
  Xpop = sicklist$Xpop,
  par = c(low
estimate,cental estimate,high estimate)[2]
  , verbose=FALSE
  )
} )
  names(dr.out) - paste(sicklist$end.point,: , names(dr.out),sep=)
  dr.out
}

#

This is where the trouble starts: What do I do if I need to pass the
argument base.conc=10 or a different option for par= to
dose.response() ? At the moment it works becuase it uses the default,
which will not be valid in all cases.

Thanks in advance
Christiaan


--
Christiaan Pauw
Nova Institute
www.nova.org.za

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide 

Re: [R] Passing arguments to a function within a function ...

2012-08-07 Thread Rui Barradas

Hello,

Your problem seems simple, if I understand it correctly. Just add an 
extra argument to the caller function, drep().



drep - function(pop.conc = x, sicklist = adult.CP.mortality,
par = cental estimate, ...) { # This extra 
argument

dr.out = by(x, x$Name, function(x) {
z = as.data.frame((x))

dose.response(pop = z$pop * sum(z[, adult.CP.mortality$Xpop]),
conc = z$conc,
cases = z$cases,
relationship = sicklist$relationship,
beta = sicklist$beta,
Xpop = sicklist$Xpop,
par = par,  # Note the difference (!)
verbose = FALSE)
})
names(dr.out) - paste(sicklist$end.point, : , names(dr.out), sep 
= )

dr.out
}


In this case, the new argument has a default value.When the callee 
dose.response() is called, the first 'par' is the name one of it's 
arguments, the second 'par' is a value, the passed to value. The first 
is a name, it does not have a value and can not, for instance, be 
printed, only the second can. They are completely different in nature.


And the same for other arguments, like 'base.conc'.

Hope this helps,

Rui Barradas

Em 07-08-2012 09:52, christiaan pauw escreveu:

Hallo Everybody

How do you specify arguments for a function used within another function?

Here is my problem:

I am reconstructing a calculator for the burden of disease due to air
pollution from publications and tools published by the WHO. The
calculations make use of published dose-response relationships for
particular health end-points. This is then applied to populations with
known or estimated levels of exposure and incidence rates to calcute
the number of cases of each end-point attributable to each pollutant.
I have functions that work on their own but when is have to use the
one within the other, I don't know how to specify its arguments

Here are example data and the functions:


## Example data frame with population, concentration and cases ##

x = data.frame(Name = LETTERS[1:10],
pop=sample(x=1000:1,size=10),
Xbabies = 0.106,
Xkids = 0.232,
Xteens = 0.375,
Xadults = 0.235,
Xaged = 0.52,
cases = sample(x=100:500,size=10),
conc = sample(x=20:125,size=10)
)

## Two of the published dose-response relationships

adult.CP.mortality = list(end.point = Cardiopulmanory mortality in
adults over 30,
   pollutant = PM10,
   relationship = log-linear,
   beta = c(0.0562,0.1551,0.2541),
   Xpop =
c(Xbabies,Xkids,Xteens,Xadults,Xaged)[4:5])

adult.LC.mortality = list(end.point = Lung Cancer mortality in adults over 30,
   pollutant = PM10,
   relationship = log-linear,
   beta = c(0.0856, 0.2322,0.3787),
   Xpop =
c(Xbabies,Xkids,Xteens,Xadults,Xaged)[4:5])

## Generic function to calculculate the Attributable cases for a
pollutant in a population
dose.response - function(pop,
   Xpop = 1,
   conc,
   base.conc=7.5,
   relationship = c(linear,log-linear)[1],
   beta=c(0.0006,0.0008,0.0010),
   cases=NULL,
   incidence.rate=NULL,
   par = c(low estimate,cental
estimate,high estimate),
   verbose = FALSE
   ){
   # Turn case rate into case number
   d - cases
   if(verbose==TRUE) message(d = , d)
   if(verbose==TRUE) message(pop = , pop)
   if(verbose==TRUE) message(beta = , beta)
   if(verbose==TRUE) message(conc = , conc)
   if(verbose==TRUE) message(base.coc = , base.conc)
   if(verbose==TRUE) message(relationship = , relationship)
   if(is.null(cases)==TRUE) {d - incidence.rate*pop} # use incidence
rate if cases are not available
   if(relationship == linear) {RR = exp(beta*(conc-base.conc))}
#RR=exp[beta(X-Xo)]
   if(relationship == log-linear) {RR = ((conc+1)/(base.conc+1))^beta}
   if(verbose==TRUE) message(RR = , RR)
   AF =  (RR-1)/RR  #AF=(RR-1)/RR
   if(verbose==TRUE) message(AF = , AF)
   AM =  AF * d #AM = AF * cases
   if(verbose==TRUE) message(AM = , AM)
   out = data.frame(beta=beta,cases=d,
RelativeRisk=RR,AttributableFraction=AF,
AttributableInsidence=AM)
   rownames(out) = c(low estimate,cental estimate,high estimate)
   if(verbose==TRUE) message(dimentions of out  = , dim(out))
   out.idx = na.omit(match(par,rownames(out)))
   out[out.idx,]
}

## Function using the  published dose-response relationships with the
generic function
drep - function(pop.conc=x,sicklist=adult.CP.mortality,...){
   

Re: [R] Passing arguments to a function within a function ...

2012-08-07 Thread christiaan pauw
Thanks Rui

It works.

On 7 August 2012 11:34, Rui Barradas ruipbarra...@sapo.pt wrote:
 Hello,

 Your problem seems simple, if I understand it correctly. Just add an extra
 argument to the caller function, drep().

Christiaan Pauw
Nova Institute
www.nova.org.za

__
R-help@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.


[R] Passing Arguments in a function

2011-02-15 Thread Michael Pearmain
Hi All,

I'm having some trouble assigning arguments inside a function to
produce a plot from a model

Can anyone help me? Below I've outlined the situation and examples of
failing and working code.

Regards

Mike



## data ##

decay.data - ...

   behaviors lift reach.uu estimated.conversions.uu total.reach
1  1 432.0083  770  7700.00
2  2 432.008329660296600.03
3  3 429.98643298500.03
4  4 427.859930320300200.03
5  5 424.010530680301100.03
6  6 418.471031180302000.03
7  7 412.002231840303600.03
8  8 405.455332340303500.03
9  9 397.008333260305600.03
1010 393.238233600305800.03
1111 385.543134940311800.03
1212 384.294235050311700.03
1313 374.029936110312600.03
1414 363.305737290313500.03
1515 353.118538450314200.03
1616 342.21904316800.03
1717 338.923240470317400.04
1818 328.866641880318800.04
1919 318.321945510335300.04
2020 308.120047230336800.04

If i use:

library(nlrwr)
# Build a model.
decay.model - nls(lift ~ SSexp(total.reach, y0, b), data = decay.data)

# plot the model
plot(decay.data[[total.reach]], decay.data[[lift]])
xv - seq(min(decay.data[[lift]]), max(decay.data[[total.reach]]), 0.02)
yv - predict(decay.model, newdata = list(total.reach = xv))
lines(xv,yv)

This works.

If i try and wrap this in a function and pass the argument values i fail when
i reach the list(total.reach = xv) i've tried various flavours or paste(),
but again can't figure out where i am going wrong, any help appreciated.

PlotDecayModel - function(x = total.reach,
   y = lift,
   data) {

  decay.model - BuildDecayModel(x= total.reach,
 y = lift,
 data = data)
  # Plot the lift Vs reach plot.
  plot(data[[x]], data[[y]])
  # Add the model curve to the plot.
  xv - seq(min(data[[x]]), max(data[[x]]), 0.02)
  yv - predict(decay.model, newdata = list(x = xv))
  lines(xv,yv)
}

I return the error
Error in xy.coords(x, y) : 'x' and 'y' lengths differ

I can see this is because the function ignores the  'newdata = list(x = xv)'
as it is trying ot assign x on the data to be xv,
(which doesn't exist in the model), so how can i use the arg total.reach so
the argument 'newdata = list(x = xv)' is evaluated as
 'newdata = list(total.reach = xv)'

Many thanks in advance

Mike

__
R-help@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.


Re: [R] Passing Arguments in a function

2011-02-15 Thread Ista Zahn
Hi Michael,

On Tue, Feb 15, 2011 at 7:15 AM, Michael Pearmain
michael.pearm...@gmail.com wrote:
 Hi All,

 I'm having some trouble assigning arguments inside a function to
 produce a plot from a model

 Can anyone help me? Below I've outlined the situation and examples of
 failing and working code.

 Regards

 Mike



 ## data ##

 decay.data - ...

   behaviors     lift reach.uu estimated.conversions.uu total.reach
 1          1 432.0083      770                      770        0.00
 2          2 432.0083    29660                    29660        0.03
 3          3 429.9864    3                    29850        0.03
 4          4 427.8599    30320                    30020        0.03
 5          5 424.0105    30680                    30110        0.03
 6          6 418.4710    31180                    30200        0.03
 7          7 412.0022    31840                    30360        0.03
 8          8 405.4553    32340                    30350        0.03
 9          9 397.0083    33260                    30560        0.03
 10        10 393.2382    33600                    30580        0.03
 11        11 385.5431    34940                    31180        0.03
 12        12 384.2942    35050                    31170        0.03
 13        13 374.0299    36110                    31260        0.03
 14        14 363.3057    37290                    31350        0.03
 15        15 353.1185    38450                    31420        0.03
 16        16 342.2190    4                    31680        0.03
 17        17 338.9232    40470                    31740        0.04
 18        18 328.8666    41880                    31880        0.04
 19        19 318.3219    45510                    33530        0.04
 20        20 308.1200    47230                    33680        0.04

 If i use:

 library(nlrwr)
 # Build a model.
 decay.model - nls(lift ~ SSexp(total.reach, y0, b), data = decay.data)

 # plot the model
 plot(decay.data[[total.reach]], decay.data[[lift]])
 xv - seq(min(decay.data[[lift]]), max(decay.data[[total.reach]]), 0.02)
 yv - predict(decay.model, newdata = list(total.reach = xv))
 lines(xv,yv)

 This works.

Actually it doesn't work for me. I get
xv - seq(min(decay.data[[lift]]), max(decay.data[[total.reach]]), 0.02)
Error in seq.default(min(decay.data[[lift]]),
max(decay.data[[total.reach]]),  :
  wrong sign in 'by' argument


 If i try and wrap this in a function and pass the argument values i fail when
 i reach the list(total.reach = xv) i've tried various flavours or paste(),
 but again can't figure out where i am going wrong, any help appreciated.

Your example is not reproducible (you don't define the BuildDecayModel
function for us...) which makes it harder to help. But just by
eyeballing...


 PlotDecayModel - function(x = total.reach,
                           y = lift,
                           data) {

  decay.model - BuildDecayModel(x= total.reach,
Putting total.reach in quotes like this just sets x equal to the
text string total.reach, not to the value of x passed to the
function. If you want the x to be passed from the function remove the
quotes.
                                 y = lift,
                                 data = data)
  # Plot the lift Vs reach plot.
  plot(data[[x]], data[[y]])
  # Add the model curve to the plot.
  xv - seq(min(data[[x]]), max(data[[x]]), 0.02)
  yv - predict(decay.model, newdata = list(x = xv))
  lines(xv,yv)
 }

 I return the error
 Error in xy.coords(x, y) : 'x' and 'y' lengths differ

 I can see this is because the function ignores the  'newdata = list(x = xv)'
 as it is trying ot assign x on the data to be xv,
 (which doesn't exist in the model), so how can i use the arg total.reach so
 the argument 'newdata = list(x = xv)' is evaluated as
     'newdata = list(total.reach = xv)'
I would try something like
nd - list(xv)
names(nd) - x
yv - predict(decay.model, newdata = nd)

 Many thanks in advance

HTH, if you still have difficulty please post a reproducible example.

Best,
Ista


 Mike

 __
 R-help@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.




-- 
Ista Zahn
Graduate student
University of Rochester
Department of Clinical and Social Psychology
http://yourpsyche.org

__
R-help@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.


[R] passing arguments to a function problem

2008-06-22 Thread Jiří Voller
Dear R-users,
is there some way how to pass various colnames to the following code for
sorting data.frames?

mydf.ordered-with(mydf, mydf[order(colname1,colname2, colnameX, decreasing
= TRUE), ])



I was trying something like

Afunction-function (mydf,colnames,decreasing=T){

 mydf.ordered-with(mydf, mydf[order(colnames, decreasing = decreasing),
])

 }

but it didnt work
please help
thank you


Jiri Voller

[[alternative HTML version deleted]]

__
R-help@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.


Re: [R] passing arguments to a function problem

2008-06-22 Thread Gabor Grothendieck
See orderBy in the doBy package.

On Sat, Jun 21, 2008 at 7:58 PM, Jiří Voller [EMAIL PROTECTED] wrote:
 Dear R-users,
 is there some way how to pass various colnames to the following code for
 sorting data.frames?

 mydf.ordered-with(mydf, mydf[order(colname1,colname2, colnameX, decreasing
 = TRUE), ])



 I was trying something like

 Afunction-function (mydf,colnames,decreasing=T){

 mydf.ordered-with(mydf, mydf[order(colnames, decreasing = decreasing),
 ])

  }

 but it didnt work
 please help
 thank you


 Jiri Voller

[[alternative HTML version deleted]]

 __
 R-help@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.

__
R-help@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.