ian - 1 year ago 107

R Question

I am trying to get nested if loops straight in my head. In trying I put together this simple script

`x<-c(1:9)`

for(i in seq(along=x)) {

if(x[i]<5){

y<-(x*3)

} else {

y<-(x*5)

}

}

It calculates an answer for me without giving an error. but the answer is wrong.

So what wrong with the script

Answer Source

I think what you really want is

```
x <- c(1:9)
y <- numeric(length(x))
for(i in seq(along = x)) {
if (x[i] < 5) {
y[i] <- x[i] * 3
} else {
y[i] <- x[i] * 5
}
}
x
# [1] 1 2 3 4 5 6 7 8 9
y
# [1] 3 6 9 12 25 30 35 40 45
```

The whole operation could be replace by a single call to `ifelse`

```
y <- ifelse(x < 5, 3 * x, 5 * x)
# [1] 3 6 9 12 25 30 35 40 45
```

`seq(along.with = x)`

or `seq(along = x)`

is correct; although `seq_along(x)`

is a faster implementation.