Phil
Phil

Reputation: 8107

Replacing values across a data frame's variables from a list of nested data frames

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"]])

Upvotes: 1

Views: 58

Answers (1)

buchmayne
buchmayne

Reputation: 154

You need to use expr! I am not sure if the subsetting will work as you tried above, but I was able to get the correct output by making a simple function and passing in an argument that was wrapped in expr()

df <- data.frame(x = rnorm(10), y = rnorm(10), z = rnorm(10))

replace_df <- list(x = data.frame(x = 1:10), 
                   y = data.frame(y = 11:20), 
                   z = data.frame(z = 21:30))

my_func <- function(string) {

  return(
    replace_df[[string]][[string]]
  )

}

df %>% 
  mutate_at(vars(x, y, z), funs(my_func(expr(.))))

Upvotes: 2

Related Questions