rif-statementcase-when

How to add a new column based on a few other variables


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]

--

structure(list(Name = c("ADI", "SLI", "SKL", "SNK", "SIIEL", "DJD"), Mon = c(1, 2, 3, 4, 5, 6), Gender = c(1, NA, NA, NA, 1, NA), Price = c(23, 34, 32, 64, 23, 34)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))

Solution

  • Using case_when() from the dplyr package:

    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)