Ask Your Question
4

How can I change a variable by evaluating multiple columns conditionally in a dplyr chain?

asked 2023-05-31 23:12:52 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-31 23:39:01 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-31 23:12:52 +0000

Seen: 8 times

Last updated: May 31 '23