I'd like to use dplyr's mutate_at
function to apply a function to several columns in a dataframe, where the function inputs the column to which it is directly applied as well as another column in the dataframe.
As a concrete example, I'd look to mutate the following dataframe
# Example input dataframe
df <- data.frame(
x = c(TRUE, TRUE, FALSE),
y = c("Hello", "Hola", "Ciao"),
z = c("World", "ao", "HaOlam")
)
with a mutate_at
call that looks similar to this
df %>%
mutate_at(.vars = vars(y, z),
.funs = ifelse(x, ., NA))
to return a dataframe that looks something like this
# Desired output dataframe
df2 <- data.frame(x = c(TRUE, TRUE, FALSE),
y_1 = c("Hello", "Hola", NA),
z_1 = c("World", "ao", NA))
The desired mutate_at
call would be similar to the following call to mutate
:
df %>%
mutate(y_1 = ifelse(x, y, NA),
z_1 = ifelse(x, z, NA))
I know that this can be done in base R in several ways, but I would specifically like to accomplish this goal using dplyr's mutate_at
function for the sake of readability, interfacing with databases, etc.
Below are some similar questions asked on stackoverflow which do not address the question I posed here:
adding multiple columns in a dplyr mutate call
dplyr::mutate to add multiple values
Use of column inside sum() function using dplyr's mutate() function
df %>% mutate_at(vars(y, z), funs(ifelse(x, ., NA)))
– eipi10ifelse(x, ., NA)
in a call tofuns()
. Thank you! I've checked your solution and that works perfectly. Your solution is exactly what I was looking for! – bschneidr