Sanjivkumark - 5 months ago 40

R Question

When i run the below function, i get the output for just one value.

with a message,

"the condition has length > 1 and only the first element will be used"

What changes do i need to make to get all values?

`ownsquare <- function(n)`

{

for (i in seq(from = 1, to = 506, by = 0.001))

{

r <- i * i

if (r <= n) x=i

}

x

}

Answer

The other way to vectorize this function is to use `ifelse`

instead of `if`

:

```
ownsquare2 <- function(n)
{
for (i in seq(from = 1, to = 506, by = 0.001))
{
r <- i * i
x <- ifelse(r <= n, i, x)
}
x
}
ownsquare2(1:10)
## [1] 1.000 1.414 1.732 2.000 2.236 2.449 2.645 2.828 3.000 3.162
```

Here, `x`

is treated as a vector in the function, and the substitution used in the `if`

expression is vectorized with `ifelse`

.

The translation from `if`

to `ifelse`

is fairly straightforward, but becomes unreadable (IMO) for chained if-else code.