Using Case_when in Rstudio to get new variable based on conditions

I am new to R and am having trouble creating a new variable using conditions from already existing variables. I have a dataset that has a few columns: Name, Month, Binary for Gender, and Price. I want to create a new variable, Price2, that will:

  1. make the price charged 20 if [the month is 6-9(Jun-Sept) and Gender is 0]
  2. make the price charged 30 if [the month is 6-9(Jun-Sept) and Gender is 1]
  3. make the price charged 0 if [the month is 1-5(Jan-May) or month is 10-12(Oct-Dec] Thank you!

This is what I am coding right now but I do not even see the new column Price2.
Data1 %>%
mutate(Price2=case_when(Mon>=6 | Mon<10 & Gender!=1 ~ 20,
Mon>=6 | Mon<10 & Gender==1 ~ 30,
TRUE~0))

We really need reproducible example (reprex)
https://community.rstudio.com/t/faq-how-to-do-a-minimal-reproducible-example-reprex-for-beginners/23061Any errors?

The code is great but we need some data. A handy way to supply sample data is to use the dput() function. See ?dput. If you have a very large data set then something like head(dput(myfile), 100) will likely supply enough data for us to work with.

Figured it out!

mydf$newprice <- dplyr::case_when(
  mydf$Mon >= 6 & mydf$Mon <= 9 & mydf$Gender == 0 ~ 20,
  mydf$Mon >= 6 & mydf$Mon <= 9 & mydf$Gender == 1 ~ 30,
  mydf$Mon < 6 | mydf$Mon > 9 ~ 0)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.