assuming I have a data set that looks something like this:
df <- data.frame("age" = c(55, 21, 11),
"sex" = c("m", "m", "f"),
"a2" = c(0,1,0),
"a3" = c(0,0,0),
"a4" = c(0,1,0),
"b2" = c(0,0,1),
"b3" = c(0,0,0),
"b4" = c(1,0,1),
"c2" = c(0,1,0)
)
age sex a2 a3 a4 b2 b3 b4 c2
55 m 0 0 0 0 0 1 0
21 m 1 0 1 0 0 0 1
11 f 0 0 0 1 0 1 0
How would I be able to transform it into long format and change the values of columns a1-c1 so that every column has the value of its name? e. g. in a2 0=1 and 1=2?
I tried it with pivot_longer like this:
df %>% pivot_longer(
cols = stars_with("a"),
names_to = "A"
)
My desired output looks like this:
age sex a2 a3 a4 b2 b3 b4 c2
55 m 1 1 1 1 1 4 1
21 m 2 1 4 1 3 1 2
11 f 1 1 1 2 1 4 1
Thanks!