Let's say I have a tibble
where I need to take multiple variables and mutate them into new multiple new variables.
As an example, here is a simple tibble:
tb <- tribble(
~x, ~y1, ~y2, ~y3, ~z,
1,2,4,6,2,
2,1,2,3,3,
3,6,4,2,1
)
I want to subtract variable z from every variable with a name starting with "y", and mutate the results as new variables of tb. Also, suppose I don't know how many "y" variables I have. I want the solution to fit nicely within tidyverse
/ dplyr
workflow.
In essence, I don't understand how to mutate multiple variables into multiple new variables. I'm not sure if you can use mutate
in this instance? I've tried mutate_if
, but I don't think I'm using it right (and I get an error):
tb %>% mutate_if(starts_with("y"), funs(.-z))
#Error: No tidyselect variables were registered
Thanks in advance!
Because you are operating on column names, you need to use
mutate_at
rather thanmutate_if
which uses the values within columnsTo create new columns, instead of overwriting existing ones, we can give name to
funs
Edit: In
dplyr 0.8.0
or higher versions,funs()
will be deprecated (source1 & source2), need to uselist()
insteadCreated on 2018-10-29 by the reprex package (v0.2.1)