Let's presume I have the following dataframe:
df <- data.frame(x = rnorm(10), y = rnorm(10), z = rnorm(10))
And I would like to replace the values in the variables by their corresponding data frame and variable names in the following list:
replace_df <- list(x = data.frame(x = 1:10),
y = data.frame(y = 11:20),
z = data.frame(z = 21:30))
How would I do that using dplyr
?
I feel like my issue is related to this Q&A, but I haven't been able to implement the answers to that question correctly to my situation.
I've attempted the below, among others, without success:
library(tidyverse)
variables <- c("x", "y", "z")
df %>%
mutate_at(vars(variables), funs(replace_df[[.]][[.]]))
The "dumb" way would be the following:
df %>%
mutate(x = replace_df[["x"]][["x"]],
y = replace_df[["y"]][["y"]],
z = replace_df[["z"]][["z"]])