Dambo
Dambo

Reputation: 3486

How to replace columns in a mutate_at with another variable from the tibble itself?

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?

Upvotes: 1

Views: 1077

Answers (1)

Scarabee
Scarabee

Reputation: 5704

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

Upvotes: 1

Related Questions