You can use mutate()
function with if_else()
function inside a dplyr chain to change a variable based on multiple column conditions. Here is an example:
library(dplyr)
df <- data.frame(
x = c(1, 2, 3, 4),
y = c(10, 20, 30, 40),
z = c(100, 200, 300, 400)
)
df %>%
mutate(new_var = if_else(x == 1 & y == 10, "yes",
if_else(z > 250, "maybe", "no")))
This code will create a new variable new_var
that will be "yes" for rows where x
is 1 and y
is 10, "maybe" for rows where z
is greater than 250, and "no" otherwise.
Asked: 2023-05-31 23:12:52 +0000
Seen: 8 times
Last updated: May 31 '23