I have a dataframe in R that contains a column with a specific character string and the week that data was obtained. I need to create a new column that returns a 0 or a 1 if the character string from the current week matches the character string from the previous week.
For example, trying to create the column "Match" below.
Thank you for your help!
Week Data Match
1 Red 0
2 Blue 0
3 Blue 1
4 Yellow 0
5 Green 0
6 Blue 0
7 Blue 1
8 Blue 1
9 Green 0
10 Yellow 0
On a slightly modified data set that includes non-consecutive Weeks, using diff
to measure the distance and lag
to test the matches.
library(dplyr)
df %>%
mutate(Match = (if_else(c(0, diff(Week)) == 1, Data == lag(Data), FALSE))*1)
Week Data Match
1 1 Red 0
2 2 Blue 0
3 3 Blue 1
4 4 Yellow 0
5 6 Green 0
6 7 Blue 0
7 8 Blue 1
8 10 Blue 0
9 11 Green 0
10 12 Yellow 0
df <- structure(list(Week = c(1, 2, 3, 4, 6, 7, 8, 10, 11, 12), Data = c("Red",
"Blue", "Blue", "Yellow", "Green", "Blue", "Blue", "Blue", "Green",
"Yellow")), row.names = c(NA, -10L), class = "data.frame")