Question

I want to have a sequence for a certain case. For this I use an ifelse statement, but I always receive zero. Here is a simple example:

seq(0,10, by=1)
[1]  0  1  2  3  4  5  6  7  8  9 10

while

ifelse (1==1, seq(0,10, by=1), seq(0,10, by=1))
[1] 0

I don't see, why I would get 0 in the second case.

Best,

Mat

Was it helpful?

Solution

Your first argument is of length one - so the output will be of length 1. It is true, so is returning the first element of your second argument, which is 0.

Maybe you want

if (1==1) {
seq(0,10, by=1)
} else {
seq(0,10, by=1)
}

Neither is a very realistic piece of code, though

OTHER TIPS

I don't think you understand the use of ifelse completely. Your condition (1 == 1) is always true, so you know the answer in advance. Moreover the result for positive and negative examples is the same.

You use ifelse to test a vector on a certain condition. If a value in the vector abides to the condition the first value is returned, if it doesn't the second one is returned. For example;

test <- sample(letters[1:2], 100, replace = T) 
ifelse(test == "a", 'is a', 'is b')

The result will always be of the same length as the input vector. If your return values have a length longer than 1, the ifelse will be aborted if the length of the input vector is reached. This implies that values in the import vector remain unevaluated. So you typically don't want to use the ifelse when your return values are longer than 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top