1

Say I have two vectors:

a<-c(6,6,NA,NA,9,9,8,NA,NA,7,NA,NA,NA,NA)
b<-c(NA,NA,NA,NA,NA,NA,NA,NA,NA,8,NA,5,7,NA)

If there is any increase in the vector, I change the values to NA.

Say, in vector a, fifth value is 9, increase from last value 6 so it will be NA and all the values afterwards. And for b vector, there is a change from 5 to 7, so 7 onward it must be NA.

Expected output:

a = c(6,6,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA)
b = c(NA,NA,NA,NA,NA,NA,NA,NA,NA,8,NA,5,NA,NA)

If there is no increase in the vector, the vector remains the same.

How to create a function to achieve this?

zx8754
  • 52,746
  • 12
  • 114
  • 209
lemon149
  • 11
  • 3

1 Answers1

2

This should probably works.

a<-c(6,6,NA,NA,9,9,8,NA,NA,7,NA,NA,NA,NA)
b<-c(NA,NA,NA,NA,NA,NA,NA,NA,NA,8,NA,5,7,NA)

foo <- function(vec){
  na.rm.vec <- vec[!is.na(vec)]
  na.rm.vec[na.rm.vec > na.rm.vec[1]] <- NA
  vec[!is.na(vec)] <- na.rm.vec
  return(vec)
}

foo(a)
# [1]  6  6 NA NA NA NA NA NA NA NA NA NA NA NA
foo(b)
# [1] NA NA NA NA NA NA NA NA NA  8 NA  5  7 NA
  • Thanks for you help so much!!! May I ask another question? Using the same two vectors as above a and b, write a function to check: when there is a decrease in the values in a vector, return a logical vector "False" if the decrease is greater than 1 from one value to another, return "true" if the decrease is actually 1 for two values next to each other. So for vector a, it should return true because9-8=1 and 8-na-na-7=1.for b it should return false because 8-na-5 can allow decreasing by 2. 8-5=3 is greater than 1. – lemon149 Dec 02 '16 at 20:19