[R] Error in if-command
arun
smartpink111 at yahoo.com
Sun Aug 12 16:51:06 CEST 2012
HI,
Your second function works:
fun2<-function(y){
if(y==2){
print("yes")}
else {print("no")}}
fun2(3)
#[1] "no"
fun2(4)
#[1] "no"
fun2(2)
#[1] "yes"
But, in the first case, it is a vector.
So, you can use:
fun3<-function(y){
numbers1<-c(4,5,9,11,17)
if(y %in% numbers1){
print("yes")}
else {print("no")}
}
fun3(8)
#[1] "no"
fun3(9)
#[1] "yes"
fun3(10)
#[1] "no"
fun3(11)
#[1] "yes"
A.K.
----- Original Message -----
From: Dominic Roye <dominic.roye at gmail.com>
To: r-help at r-project.org
Cc:
Sent: Sunday, August 12, 2012 6:12 AM
Subject: [R] Error in if-command
Hello everybody,
I don't understand what I'm doing wrong. But it isn't possible that each
element of the if-condition is tested for each vector element?
y <- c(1:20)
> y
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
> if (y == c(4,5,9,11,17)) { print("yes") } else { print("no")}
[1] "no"
warning:
In if (y == c(4, 5, 9, 11, 17)) { :
Condition has length > 1 and only the first element is used
>
#It also doesn't work with this condition ==2
if (y == 2) { print("yes") } else { print("no")}
[1] "no"
warning:
In if (y == 2) { :
Condition has length> 1 and only the first element is used
I guess it's a trivial problem. I hope someone can help me.
Thank you!
[[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.
More information about the R-help
mailing list