1

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?

hpmurg
  • 97
  • 7
  • 2
    This is how `ifelse` is designed. https://stackoverflow.com/questions/1335830/why-cant-rs-ifelse-statements-return-vectors – Anonymous coward Nov 28 '18 at 16:09
  • Hi! I already saw the question to the link, but _I couldn't figure the appropiate solution out for my case – hpmurg Nov 28 '18 at 16:15
  • 1
    Use `if` and `else`, instead of `ifelse`. For example, `x <- if(1 == 2) 1:10 else 21:30` is equivalent to `x <- 21:30` – IceCreamToucan Nov 28 '18 at 16:17
  • @IceCreamToucan Thanks! Didn't know it worked like this as well. – hpmurg Nov 28 '18 at 16:29
  • What do you mean by "if difference of median values is bigger than 50%"? Difference with what? – Ben G Nov 28 '18 at 16:31
  • @BenG : if (absolute) difference of first two unique values is bigger than 50% of first unique value – hpmurg Nov 28 '18 at 16:33
  • 2
    Possible duplicate of [Why can't R's ifelse statements return vectors?](https://stackoverflow.com/questions/1335830/why-cant-rs-ifelse-statements-return-vectors) – prosoitos Nov 28 '18 at 16:39

0 Answers0