I have a dataframe that looks like this (but with hundreds of columns):
df_in <-
data.frame(
x_1 = 0:3,
x_2 = 30:33,
x_3 = 20:23,
y_1 = c("a", "c", "b", "c"),
y_2 = c("b", "a", "c", "b"),
y_3 = c("c", "b", "a", "a"))
Let's say that the y columns contain the names of sports teams (a, b, c); x variables, linked to y variables by the column index number, is the number of goals that team scored; each row represents a 3-way contest.
For each contest I want create new columns capturing the performance of two of the teams, a and b. This is the output I want, using long-hand approach:
df_in %>%
mutate(
a_value =
case_when(
y_1 == "a" ~ x_1,
y_2 == "a" ~ x_2,
y_3 == "a" ~ x_3),
b_value =
case_when(
y_1 == "b" ~ x_1,
y_2 == "b" ~ x_2,
y_3 == "b" ~ x_3))
I need to make this more concise, given that there are many more columns in the real data. I'm guessing there's a tidyverse way to do this but I'm unsure.