. Advertisement .
..3..
. Advertisement .
..4..
Hi developer experts,
I have a small but frustrating use case, and so far, I couldn’t get my head around this problem & ideal solution. I am running my program, and I am facing one problem with the the condition has length > 1 and only the first element will be used.
Below is the command I used:
a <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
w<-function(a){
if (a>0){
a/sum(a)
}
else 1
}
when I run it, I get the following error:
Warning message:
In if (a > 0) { :
the condition has length > 1 and only the first element will be used
I am looking forward to gaining some knowledge from all experts. Thank you, guys!
The error occured because you intended to pass f() a vector with length > 1.
In R, if() and else() can only react to one logical element (true or false) at 1 time.
The options I might suggest you are:
1. use sapply(t, f)
2. or use ifelse() because ifelse() can react to a logical vector with length > 1.
Below is my example of using ifelse()
The
if
statement cannot be vectorized.ifelse
is recommended for vectorized if statements. It is enough to write in your caseOr a shorter vectorised version
It all depends on which function you use. First function produces an output vector of length 1, while
ifelse
generates an output vector equal toa
.Maybe you are interested in
ifelse