-4

I have a sequence of numbers that I want to check and reject numbers that do not increase with similar level.

data <- c(1, 2, 5, 6, 6.25, 6.49, 6.75, 7.01, 8, 9, 11)

For example, for the data here I want to subset numbers with an increase of 0.25+/-0.1, and reject numbers that do not follow this rule. In this case, the subseted sequence would be (6, 6.25, 6.49, 6.75, 7.01).

Xcodian Solangi
  • 2,342
  • 5
  • 24
  • 52
Jian
  • 365
  • 1
  • 6
  • 19
  • 2
    Welcome to SO. This site is not a code-writing service and is not meant for delivering complete solutions. Users are expected to show some effort and code whilst SO is here to help you solve specific programming problems along the way. Have you tried anything already? Please read: https://stackoverflow.com/help/asking – Maciej Jureczko Oct 05 '17 at 19:38

1 Answers1

-1

Here's an ugly way to grab the indexes that you want to keep. Change 0.35 if you're interested in a different cutoff value

myfun <- function(D) {
            index <- unique(c(which(abs(diff(D)) < 0.35), which(abs(diff(D)) < 0.35)+1))
            return(sort(index))
        }

Call the function to obtain the answer you want with

data[myfun(data)]
# [1] 6.00 6.25 6.49 6.75 7.01

Another test

test <- c(1, 1.25, 2, 2.25, 3, 4.5, 4.75, 5, 5.45, 5.65)
test[myfun(test)]
# [1] 1.00 1.25 2.00 2.25 4.50 4.75 5.00 5.45
CPak
  • 13,260
  • 3
  • 30
  • 48
  • You can remove the `dplyr` dependency by replacing `which(dplyr::lag(abs(diff(D)) < 0.35, 1))` with `which(abs(diff(D)) < 0.35) + 1`. The `lag` essentially just adds one to the TRUE indices. – Gregor Thomas Oct 05 '17 at 19:50
  • I did mention it was ugly – CPak Oct 05 '17 at 19:53