I have a dataframe with a factor column with j levels, as well as j vectors of length k. I would like to populate k columns in the former dataframe with values from the latter vectors, conditional on the factor.
Simplified example (three levels, three vectors, two values):
df1 <- data.frame("Factor" = rep(c("A", "B", "C"), times = 5))
vecA <- c(1, 2)
vecB <- c(2, 1)
vecC <- c(3, 3)
Here is a solution using nested ifelse statements:
library(tidyverse)
df1 %>%
mutate(V1 = ifelse(Factor == "A", vecA[1],
ifelse(Factor == "B", vecB[1], vecC[1])),
V2 = ifelse(Factor == "A", vecA[2],
ifelse(Factor == "B", vecB[2], vecC[2])))
I would like to avoid the nested ifelse statements. Ideally, I would also like to avoid mutating each column separately.