I have the following dataframe. And I need to replace unique values above 0 with numbers starting with 1 within each group? I understand how to replace values within a column or within a row but not within a whole group.
df <- data.frame(
group = c("A","A","B","B","C"),
value1 = c(55, 0, 92, 93, 173),
value2 = c(55, 0, 92, 93, 174),
value3 = c(66, 77, 92, 0, 175)
)
print(df)
group value1 value2 value3
1 A 55 55 66
2 A 0 0 77
3 B 92 92 92
4 B 93 93 0
5 C 173 174 175
And here is what I need to get:
group value1 value2 value3
1 A 1 1 2
2 A 0 0 3
3 B 1 1 1
4 B 2 2 0
5 C 1 2 3
I tried to do it using mutate
, across
and dense_rank
functons.
df <- df %>%
group_by(group) %>%
mutate(across(-group, ~ifelse(. > 0, dense_rank(.), .))) %>%
ungroup()
But got an error:
Error: Problem with `mutate()` input `..1`.
x Can't subset columns that don't exist.
x Column `group` doesn't exist.
i Input `..1` is `across(-group, ~ifelse(. > 0, dense_rank(.), .))`.
i The error occurred in group 1: group = "A".