Viktor Plattner - 3 months ago 22

R Question

probably it's a very simple question with a very simple answer but I just can't figure it out by myself. I have a matrix called 'hz' with 1 column and 115 rows (hz[1:115, 1]) and I'm trying to find the values preceding those that are smaller than 1 and replace them. I did the following:

`hz[c(hz < 1)]`

then I tried to find the preceding ones:

`hz[c(hz < 1) - 1]`

If I try to find specific elements like

`hz[c(6, 26, 36)]`

`hz[c(6, 26, 36) - 1]`

Thank you for your help!

Viktor

Answer

Basically you want `hz[which(hz < 1) - 1]`

.

Note, `hz < 1`

is returning a logical vector, i.e., `TRUE`

/ `FALSE`

. If you take subtraction: `(hz < 1) - 1`

, `TRUE`

will be seen as `1`

and `FALSE`

will be seen as `0`

. Applying `which`

to a logical vector gives you positions (as integers) of `TRUE`

, which is what you want.

Consider the following demonstration:

```
x <- 1:5
x < 3
#[1] TRUE TRUE FALSE FALSE FALSE
(x < 3) - 1
#[1] 0 0 -1 -1 -1
which(x < 3)
#[1] 1 2
which(x < 3) - 1
#[1] 0 1
```