I have the following dataframe:
have <- structure(list(a1 = c(1, 1, 0, 1, 1, 1, 1, 1, 1, 1), a2 = c(1,
1, 0, 1, 1, 0, 1, 1, 1, 1), b1 = c(0, 0, 0, 0, 0, 1, 0, 0, 0,
0), b2 = c(1, 1, 0, 0, 0, 1, 0, 0, 0, 0), c1 = c(0, 0, 0, 0,
1, 0, 0, 0, 0, 0), c2 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), id = 1:10),
row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"))
For variables a1:c2, whenever value is 1, I need to replace it for the id value (of the same row). Whenever value is zero, I need to replace it for missing (NA_real).
Preferably with dplyr and case_when, that I am more used to.
So, the expected output is:
want <- structure(list(a1 = c(1, 2, NA, 4, 5, 6, 7, 8, 9, 10), a2 = c(1,
2, NA, 4, 5, NA, 7, 8, 9, 10), b1 = c(NA, NA, NA, NA, NA, 6, NA, NA, NA,
NA), b2 = c(1, 2, NA, NA, NA, 6, NA, NA, NA, NA), c1 = c(NA, NA, NA, NA,
5, NA, NA, NA, NA, NA), c2 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), id = 1:10),
row.names = c(NA,-10L), class = c("tbl_df", "tbl", "data.frame"))
What I have tried is:
library(dplyr)
want <- have %>%
mutate(across(c(a1:c2),
.fns = ~ case_when(. == 1 ~ id,
T ~ NA_real_))
)
But it doesnt work, I get the error:
Error in `mutate()`:
! Problem while computing `..1 = across(c(a1:c2), .fns = ~case_when(. == 1 ~ id,
T ~ NA_real_))`.
Caused by error in `across()`:
! Problem while computing column `a1`.
Caused by error in `` names(message) <- `*vtmp*` ``:
! 'names' attribute [1] must be the same length as the vector [0]
Backtrace:
1. have %>% ...
8. dplyr::case_when(a1 == 1 ~ id, T ~ NA_real_)
9. dplyr:::replace_with(...)
10. dplyr:::check_type(val, x, name, error_call = error_call)
11. rlang::abort(msg, call = error_call)
...
16. rlang::cnd_message(c)
17. rlang:::cnd_message_format(cnd, ...)
18. rlang (local) cli_format(glue_escape(lines))
19. rlang:::.rlang_cli_format(x, cli::format_error)
20. cli::cli_format(x, .envir = emptyenv())