Aditya Vijaikumar
Aditya Vijaikumar

Reputation: 3

Compare the present value with the previous value in R while in ifelse()

I was working on a project in which if I want to compare the present value with the previous value and return an output 1 if true and 0 if false.

I tried

brv_trx1$'first' <- ifelse(brv_trx1$`Total TRx` != lag(brv_trx1$`Total TRx`),1,0)

This code did not work as expected.

x= c(1,2,2,2,3,4,5,5,5,5,6,7)

I wanted an output similar to this:

x  y
1  1
2  1
2  0
2  0 
3  1
4  1 
5  1
5  0
5  0

After this step I have a decile function

brv_trx1$decvar <- ifelse(brv_trx1$cum != 0 & brv_trx1$first == 1, (11 - ceiling(round((brv_trx1$cum/total) * 10, 4))), 
                     ifelse(brv_trx1$cum != 0 & brv_trx1$first == 0 , lag(brv_trx1$decvar), 0))

For this function, I was getting a lot of NAs.

The output expected was :

Y Dec
1 10
1 10
1 9
0 9
0 9
1 8
0 8
1 8
1 8

Upvotes: 0

Views: 609

Answers (3)

A. Suliman
A. Suliman

Reputation: 13135

Using diff

ifelse(c(1,diff(x))==0,0,1)
[1] 1 1 0 0 1 1 1 0 0 0 1 1

Upvotes: 0

Josh Kay
Josh Kay

Reputation: 66

Because lag() will produce NA for the first entry, consider the following:

x= c(1,2,2,2,3,4,5,5,5,5,6,7)
x <- as.data.frame(x=x)

x$y <- ifelse( (x$x==lag(x$x)) %in% c(NA, FALSE), 1, 0) 

If the comparison of x == lag(x) is FALSE or NA (because it's the first comparison of the lag), flag 1, else flag 0 per your example above.

Upvotes: 1

Balter
Balter

Reputation: 1095

You can use indexes. Here I've made vectors that go from 1-9, and 2-10. Then you compare the elements of your original vector by using the "shifted by 1" indexes (1 compares to 2, 2 compares to 3, etc).

x <- c(1,2,2,3,4,4,4,5,6,7)
length(x)
#[1] 10

i.1 <- 1:(length(x)-1)
i.2 <- 2:length(x)

x[i.1] == x[i.2]
#[1] FALSE  TRUE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE

Upvotes: 0

Related Questions