ifelse() should work too. Andrew
On Sun, Oct 09, 2005 at 03:30:42PM +1000, sosman wrote: > nawaf b wrote: > > Hi - > > > > I was wondering if anyone came across a problem such as mine! I was trying > > to create a user-defined function, however, the results from calling the > > function are unexpected! > > > > When passing X parameter as a single value variable (x<-c(3)), everything > > works fine. However, when passing a parameter as a vector with multiple > > values (as the case in my code), the 'if condition' is only executed once! > > > > Here is my code: > > > >>x > > > > [1] 0.3 1.0 0.7 22.0 > > > >>myfunction<-function(x) > > > > + { > > + if (x>=1) 0 > > + else x^2 > > + } > > > >>myfunction(x) > > > > [1] 0.09 1.00 0.49 484.00 > > Warning message: > > the condition has length > 1 and only the first element will be used in: if > > (x >= 1) 0 else x^2 > > > > > > Is there a way to overcome this issue? Can you please explain what > > modifications to the code I need to accommodate to make it work. > > I am going to go out on a limb here (I don't know much about R) but I'm > not sure it has anything to do with that fact that you have defined a > function. > > It seems to me that "if (x > 1) {...}" expects a scalar and if x is not > a scalar, it will use the first value. To apply your function to each > element, check out the help for sapply (eg ?sapply). I am guessing the > solution is something like sapply(x, myfunction) but don't quote me. > > paul sorenson > > ______________________________________________ > R-help@stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html -- Andrew Robinson Senior Lecturer in Statistics Tel: +61-3-8344-9763 Department of Mathematics and Statistics Fax: +61-3-8344-4599 University of Melbourne, VIC 3010 Australia Email: [EMAIL PROTECTED] Website: http://www.ms.unimelb.edu.au ______________________________________________ R-help@stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html