Viktor Plattner Viktor Plattner - 2 months ago 12
R Question

finding n-1 matrix elements in R

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)]
, got 11 values,
then I tried to find the preceding ones:
hz[c(hz < 1) - 1]
, expected 11 values but got 114.
If I try to find specific elements like
hz[c(6, 26, 36)]
, and the preceding ones:
hz[c(6, 26, 36) - 1]
I got 3 values in both cases as expected. So what's the difference? Is it a problem that I have a condition (<1) in the index?

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