Search code examples
rloopsif-statementseq

Using seq() and ifelse in a for loop


I'm trying to make the following "sequence":

0.0025,0.005, 0.010, 0.015, 0.020, 0.025, 0.030, 0.035, 0.040, 0.045, 0.050, 0.055, 0.060

As you can see, after the first value 0.0025, the values increase by 0.0025 and then continuously by 0.005. So after the second value of 0.005, it is essentially a sequence increasing by 0.005. Which I thought I could use seq() in.

What I thought would work would be:

    matrix1 <- matrix("", nrow = 1, ncol = 13)
    m <-  for (i in 1:length(matrix1){

    matrix1[,i] <- ifelse(i == 1, 0.0025, ifelse(i == 2, 0.005, seq(0.01,    0.05, by = 0.005)))
}

This however gives me the following result:

     [,1]     [,2]    [,3]   [,4]   [,5]   [,6]   [,7]   [,8]   [,9]   [,10]  [,11]  [,12]  [,13] 
[1,] "0.0025" "0.005" "0.01" "0.01" "0.01" "0.01" "0.01" "0.01" "0.01" "0.01" "0.01" "0.01" "0.01"

Which is not what I want.

Any suggestions?


Solution

  • If the question is really about using a for loop, then I'd rather use if and else statements:

    n <- 13
    x1 <- vector("numeric", 13)
    for (i in 1:n) {
      if (i==1) {
        x1[i] <- 0.0025
      } else {
        x1[i] <- 0.005 + (i-2)*0.005
      }
    }
    

    ... because ifelse is meant to be applied on vectors :

    j <- 1:n
    x2 <- ifelse(j == 1, 0.0025, 0.005 + (j-2)*0.005)
    

    But there are so many other ways to get the required result! My favorite is

    x3 <- c(0.0025, seq(0.005, 0.06, by=0.005))
    

    because when you read it aloud, you really create a vector for which", after the first value 0.0025, the values increase by 0.0025 and then continuously by 0.005."