user1945827 - 4 months ago 13

R Question

I want to check whether or not a value is within a range or not; if it is present, insert a value; else do nothing.

Say I have some two (or more) vectors,

`A <- c(1.1, 3.4, 5.5, 10.2)`

B <- c(1.1, 3.4, 5.5, 8.01, 10.2)

If I look at vector A for the presence of a number in the range 7.8 to 8.2, since there isn't one there I want to insert the number 8.01.

When I look at vector B and test whether or not there is a number in the range 7.8 to 8.2, since one is present; I don't want to do anything.

It looks simple but I'm missing something. Any help would be gratefully received.

Answer

Consider this toy function for general implementation. `x`

is the input vector, `l`

and `u`

are lower and upper bound, while `x0`

is the value to insert (if insertion turns out needed).

```
foo <- function (x, l, u, x0) {
z1 <- x > l
z2 <- x < u
if (sum(z1 & z2)) x
else append(x, x0, which(z1)[1] - 1)
}
A <- c(1.1, 3.4, 5.5, 10.2)
B <- c(1.1, 3.4, 5.5, 8.01, 10.2)
foo(A, 7.8, 8.2, 8.01)
#[1] 1.10 3.40 5.50 8.01 10.20
foo(B, 7.8, 8.2, 8.01)
#[1] 1.10 3.40 5.50 8.01 10.20
```