I have a dataframe where I tried to assign variables "I" for each unique value in the "id" column using the code below. However, the assigned values are treated as characters instead of variables. How can I convert them into variables? I am looking for a more efficient approach as my actual dataset has a larger number of individuals, making manual assignment impractical.
df <- data.frame(
id = c("a", "a", "a", "b", "b", "b", "c", "c", "c", "c")
)
I1 <- 1
I2 <- 2
I3 <- 3
df2 <- df %>%
dplyr::mutate(I = paste0("I", as.integer(factor(id))))
df2
id I
1 a I1
2 a I1
3 a I1
4 b I2
5 b I2
6 b I2
7 c I3
8 c I3
9 c I3
10 c I3
One workaround I found is the code below, but I believe there should be a more efficient solution.
df3 <- df2 %>%
dplyr::mutate(I = case_when(
id == "a" ~ I1,
id == "b" ~ I2,
id == "c" ~ I3
))
df3
id I
1 a 1
2 a 1
3 a 1
4 b 2
5 b 2
6 b 2
7 c 3
8 c 3
9 c 3
10 c 3
I would appreciate any idea to do this effectively. Thank you.