Home > Mobile >  Conditionally Remove Values in an Vector Base on Previous Value
Conditionally Remove Values in an Vector Base on Previous Value

Time:05-17

I have a vector of 1-60 values, that could only be one of three values

For example:

x <- c("VAL1","VAL1","VAL1","VAL2","VAL2","VAL3","VAL3","VAL3","VAL3","VAL1")

I would like to condense this vector by removing values base on the previous value, ie. remove n 1 if n = n 1, but if n != n 1 return n and n 1

The desired output would look like this:

x <- c("VAL1","VAL2","VAL3","VAL1")

I think am going to need to use a for loop, checking where i matches i 1, but I am having trouble with the syntax

CodePudding user response:

We can use rle from base R instead of using a for loop

rle(x)$values
[1] "VAL1" "VAL2" "VAL3" "VAL1"

CodePudding user response:

You could also use indexing

x[c(x[-1] != x[-length(x)], TRUE)]

[1] "VAL1" "VAL2" "VAL3" "VAL1"

CodePudding user response:

I think the simplest approach is using rle (as done by @akrun), or using the lagged difference by @onyambu.

If you want to have a practice of coding with for loops, you can try

res <- x[1]
for (i in 2:length(x)) {
    if (x[i] != x[i - 1]) {
        res <- append(res, x[i])
    }
}
  • Related