# Re: [R] default values

Date: Wed, 12 Mar 2008 14:40:47 -0400

You just need to return the values computed when a==0 and when a!=0.

a=0
f=function(x,y,z=0) {

if (a==0) return(x[1]+x[2]+y)
if (a!=0) return(x[1]+x[2]+y+z)
}

> f(1:2,3)

[1] 6
>

Ravi.

Assistant Professor, The Center on Aging and Health

Division of Geriatric Medicine and Gerontology

Johns Hopkins University

Ph: (410) 502-2619

Fax: (410) 614-9625

I wrote the following toy example to explain my problem :

a=0
f=function(x,y,z) {

I have not specified z and I get an error. Although a=0, R seems to want to know z because it's in the expression x[1]+x[2]+y+z.

So I tried to put a default value :

a=0
f=function(x,y,z=0) {

if (a==0) x[1]+x[2]+y
if (a!=0) x[1]+x[2]+y+z
}
f(1:2,3)

Why isn't it working ? Sometimes everything is fine even though a parameter is not specified.

Thanks a lot.

[[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.

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 12 Mar 2008 - 18:45:04 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 12 Mar 2008 - 19:30:22 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.