0

I'm using R, 310 (64 bit) I'm trying to create a vector of predetermined length (201) to be used as y-axis-range for an empty plot fucntion, to be filled in later.

I want to set a minimum max-value to this vector (5 000 000) to keep a somewhat uniform plot, while dealing with eventual entries of differing, and sometimes higher maximum.

A simple if-else statement should do it (see example code). However, I bump into something strange that, for the life of me, I cannot explain. When using the vectorized ifelse() command I get a completely different and very wrong answer compared with the standard if-else command structure. I tried setting the individual and all elements in brackets, e.g. ifelse((condition),(true),(false)), but to no avail.

Here it doesn't matter much for what I want to do, but I really want to understand what's happening here as I am certain I'll get stuck on this at some point when it does matter that I use the ifelse() command.

Unfortunately, there is no error message that may help me further into understanding what R is doing with these commands, so your answers will be appreciated.

thanks in advance Rudolf

n.group <- c(2504576,2208945,1500043,90672,57432,345961,239856,138742,73890,23745,9348,5213,300)
y.axis  <- c(100,250,500,1000,2500,5000,10000,50000,100000,500000,1000000,5000000)

y.range <- ifelse(max(n.group) < 5000000, seq(1, max(y.axis), length.out=201), seq(1, max(n.group), length.out=201))

> y.range
 [1] 1       ## why just 1, it should be a vector with length 201?
             ## what goes wrong here?

max(n.group) < 5000000
 [1] TRUE            ## so, the ifelse should lead to a sequence with maximum 5 000 000

seq(1, max(y.axis), length.out=201)
 [1]       1.00   25000.99   50000.99   75000.99  .......
 [201] 5000000.00              ## thus my seq() command works

# what if I devectorize my ifelse?
if(max(n.group)<5000000){
         y.range <- seq(1, max(y.axis), length.out=201)
}else     {
         y.range <- seq(1, max(n.group), length.out=201)}
> y.range
  [1]       1.00   25000.99   50000.99 ........
  [201] 5000000.00            ### now I get the vector of length = 201  ???
  • 3
    `ifelse` is not an equivalent of `if (...) {} else {}`. The first one always returns value of the same shape as test. In your case it is a vector of length one. You can find details in `?ifelse`. – zero323 Jun 08 '15 at 16:04
  • thanks @zero323, I understand now. – Rudolf Talens Jun 18 '15 at 10:01

0 Answers0