mardi 20 juin 2017

R - Test if value is the same as the one in the cell above

I have the following df:

name   color
A      red 
B      red
C      green
D      red
E      red
F      red

And I want to test the values in the 'color' column to see if they're the same as the values in the row above and write to a new column... I can do so using the following:

> df$same <- ifelse(df$color == df$color[c(NA,1:(nrow(df)-1))], 1, 0)

To give me:

name   color  same
A      red      NA
B      red       1
C      green     0
D      red       1
E      red       1
F      red       1

But is there a cleaner way to do it? (I use this all the time)...

Aucun commentaire:

Enregistrer un commentaire