Domanda

I have a vector like

    a <- c(4,2,7,6,8,9,3,1,12,13)

I would like to replace all elements that are smaller than previous ones with NA's, that result for my example should be:

    [1]  4 NA  7 NA  8  9 NA NA 12 13

i thought about using a for-loop but could not come up with a solution. Any other options?

(My next step would be to replace the NA'y by linear interpolation using na.approx())

Thanks for the hint to use diff(). However, I recognized that my example above doesn't cover all cases in my dataset, so this is a better one: For vector

    b <- c(4,2,7,6,8,9,3,1,5,7,12,13)

I would like to get

    [1]  4 NA  7 NA  8  9 NA NA NA NA 12 13

while

    b[diff(c(b[1], b)) < 0] <- NA

gives me

    [1]  4 NA  7 NA  8  9 NA NA  5  7 12 13
È stato utile?

Soluzione 2

I think you're looking for cummax:

b[b < cummax(b)] <- NA
# [1]  4 NA  7 NA  8  9 NA NA NA NA 12 13

Altri suggerimenti

You can just use diff and regular extraction/subsetting:

a[diff(c(a[1], a)) < 0] <- NA
a
#  [1]  4 NA  7 NA  8  9 NA NA 12 13

(Here, I'm assuming < 0 is what you're looking for since it matches with your output, even though it doesn't fully match with your description, which simply mentions "less than the previous one".)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top