No wonder I didn't get the warning message (but the same wrong plot).
Qian
On Wed, 27 Feb 2008 08:21:10 -0500
"Jens Hainmueller" <jhainmueller at gmail.com> wrote:
Jeremy,
The issue here is similar to my previous email, but slightly different. The
error:
the condition has length > 1 and only the
first element will be used
always occurs when you use an if(candition) statement, but the condition
evaluates to a vector of length k with k>1 (like c(TRUE,FALSE) or so). In
this case it is unclear which element R should use (ie. the TRUE or the
FALSE) so by default it goes with the first statement and also issues a
warning.
In this case, the ifelse() command (that triggers a different action
depending on element by element checking of the condition) is your best bet
to make the function work with vectors. See me previous email and Quan?s on
this.
Jens
From: gov2001-l-bounces at
lists.fas.harvard.edu
[mailto:gov2001-l-bounces at
lists.fas.harvard.edu] On Behalf Of Jeremy Hodgen
Sent: Wednesday, February 27, 2008 2:37 AM
To: gov2001-l at
lists.fas.harvard.edu
Subject: Re: [gov2001-l] Qu2
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
_______________________________________________
gov2001-l mailing list
gov2001-l at
lists.fas.harvard.edu
http://lists.fas.harvard.edu/mailman/listinfo/gov2001-l