mercredi 28 novembre 2018

When Ifelse statement is true, ifelse only returns one value instead of all

I have this data frame:

> new


     median
1    3.957587 
2    3.957587 
3    3.957587 
4    3.957587 
5    3.957587 
6    3.957587 
7    3.249960 
8    3.249960 
9    3.249960 
10   3.249960 
11   3.249960 
12   3.249960 
13   2.962515 
14   2.962515
15   2.962515 
16   2.962515 
17   2.962515 
18   2.962515

Now I compare these median values with this command:

# if difference of median values is bigger than 50%, get index of where this is happens
# returns numeric(0) when condition not met

results <- which(c(0, abs(diff(new$median))) > 0.5 * new$median) - 1

This works fine.

What I want to do now, is when the difference of median values is less than 50% (condition not met), just get the index of where the median values change. I could do it this way:

> testing <-  which(new$median[-1] != new$median[-length(new$median)])
> testing
[1]  6 12

I put these two ideas in an ifelse statement:

> results <- ifelse(length(results) == 0, testing, results)
> results
[1] 6

But this just gives me the first number, not also the second. Why?

Aucun commentaire:

Enregistrer un commentaire