The same thing happened to me when I wrote my function as:
g <- function(x){
ifelse(x>=(-pi/2) & x<=(pi/2), out <- 10*sin(x)*cos(x), out <-
sin(x)*cos(x))
out
}
As you said, it worked well for individual values - in fact, it worked fine for the
optimization
as well, but not for the graph.
Then I changed my program to
g <- function(x){
out <- ifelse(x>=(-pi/2) & x<=(pi/2), 10*sin(x)*cos(x), sin(x)*cos(x))
out
}
For no reason I know of, it works. It seems that in the previous case, R somehow always
treats
x>=(-pi/2) & x<=(pi/2) as false if any x in a vector falls out of this range.
Why moving "out" out
of the ifelse function would fix the problem is beyond me.
Qian
On Wed, 27 Feb 2008 07:36:57 +0000
Jeremy Hodgen <jeremy.hodgen at kcl.ac.uk> wrote:
Can anyone help?
I'm trying to define the function for qu2
This works fine for individual values of x:
g <- function(x){
if ((x < pi/2) & (x > -1*pi/2)) (y <- 10*sin(x)*cos(x)) else (y <-
sin(x)*cos(x))
return(y)
}
But when I input a vector (in order to draw the graph) like this:
ruler <- seq(-2*pi, 2*pi, by=.01)
g(ruler)
I get this error message:
Warning message:
In if ((x < pi/2) & (x > -1 * pi/2)) (y <- 10 * sin(x) * cos(x))
else (y <- sin(x) * :
the condition has length > 1 and only the first element will be used
It seems I've got too many conditions for 'if' when the input is a
vector. When I draw the
graph of g(ruler)~ruler, I get sinxcosx on the domain [-2pi, 2pi]. Any ideas on what I
could do
differently?
Thanks
Jeremy
Dr Jeremy Hodgen
Senior Lecturer in Mathematics Education
King's College London
Department of Education and Professional Studies
Franklin-Wilkins Building
Waterloo Bridge Wing
150 Stamford Street
London SE1 9NH
Tel: 020 7848 3102
Fax: 020 7848 3182
E-mail: jeremy.hodgen at kcl.ac.uk