1

I'm trying to replace multiple columns in mtcars with a variable from mtcars itself.

For instance, this is the code for replacing using a scalar:

mutate_at(.tbl = mtcars, vars(mpg, carb), function(x) 1)

Now, I would like to be able to pass for instance disp to replace the values in mpg and carb

I tried:

mutate_at(.tbl = mtcars, vars(mpg, carb), funs(function(x = .tbl) x[['disp']]))

Error in mutate_impl(.data, dots) : Column mpg is of unsupported type function

But I would rather prefer a solution that allows passing unquoted names. For instance, can I coerce funs() to look only into the environment that is being mutated?

Dambo
  • 3,318
  • 5
  • 30
  • 79
  • plain and simple : `mtcars %>% mutate(mpg = disp, carb = disp)`? But I am sure this is not what you are looking for? – tjebo Feb 21 '18 at 22:56
  • 1
    `mutate_at(.tbl = mtcars, vars(mpg, carb), funs(.data$disp))`? – Scarabee Feb 21 '18 at 23:45
  • @Scarabee why is it `.data` and not `.tbl`? From the documentation it does not look like there is any argument `.data`. Also, could you tweak your solution to extract using the `[`? – Dambo Feb 22 '18 at 04:56
  • @Scarabee The quoted rlang version: https://stackoverflow.com/questions/48891072/how-to-use-tidyeval-on-a-column-to-mutate/48892458#48892458 – acylam Feb 22 '18 at 19:07

1 Answers1

1

You can use:

mutate_at(.tbl = mtcars, vars(mpg, carb), funs(.data$disp))

(or equivalently replace .data$disp with .data[["disp"]]).


Now to answer the question you asked in a comment:

why is it .data and not .tbl?

Because .data is not the name of one of the function's arguments, but the pronoun from rlang. (See ?rlang::.data) So here .data refers to the data provided via the .tbl argument.

Note that you can never use an argument's name in the definition of another argument of the same function call. For instance consider the + function from base R. It has 2 arguments, namely x and y (as you can see in ?"+").

`+`(x = 2, y = 2)
# [1] 4

but

`+`(x = 2, y = x)
# Error: object 'x' not found
Scarabee
  • 5,437
  • 5
  • 29
  • 55