Assume the following data:
set.seed(1)
df <- data.frame(name = rep(letters[1:3], 5),
condition = sample(0:1 , 15, replace = TRUE))
df
name condition
1 a 0
2 b 1
3 c 0
4 a 0
5 b 1
6 c 0
7 a 0
8 b 0
9 c 1
10 a 1
11 b 0
12 c 0
13 a 0
14 b 0
15 c 0
I now want to go through my data frame row by row after grouping by name and when the condition is met I want to add an asterisk (*) to the name column. If the condition is not met I want to replace the name value by the previous name value.
- So in row 2, I'd like to change "b" to "b*".
- In row 5, I want to change "b*" (because that's what we already changed row 2 to) to "b**".
- In row 8, the condition is not met, so I just like to keep the previous b value, which is "b**".
I thought I can outsmart R by using a simple case_when solution, but apparently I failed with the code below. Any ideas?
library(tidyverse)
df %>%
group_by(name) %>%
mutate(helper_id = 1:n(),
name = case_when(condition == 1 & helper_id == 1 ~ paste0(name, "*"),
condition != 1 & helper_id == 1 ~ name,
condition == 1 & helper_id != 1 ~ paste0(lag(name), "*"),
condition != 1 & helper_id != 1 ~ lag(name))) %>%
ungroup()
This code adds an asterisk when the condition is met, but it doesn't take the previous/lagged name value if the condition is not met. I guess the problem is that the case_when doesn't go through the whole thing row by row.