I have a dataset with multiple columns - all filled with zeros - and one numeric index column. Now I would like to replace the zero within the column that match the column index (1 = first column, 2 = second column...)
Simplified example:
input <- tibble(X1 = c(0,0,0,0), X2 = c(0,0,0,0), X3 = c(0,0,0,0), index = c(1,2,2,3))
output <- tibble(X1 = c(1,0,0,0), X2 = c(0,1,1,0), X3 = c(0,0,0,1), index = c(1,2,2,3))
I already found one solution, but I'm curious if there is a better/easier way to write it (maybe with base R).
input %>%
select(index) %>%
bind_cols(map2_dfc(.x = c('X1', 'X2', 'X3'),
.y = 1:3,
.f = ~input %>%
transmute(!!sym(.x) := if_else(.y == index, 1, 0))))`