rdplyrnon-standard-evaluationstandard-evaluation

SE issue with conditional mutate


I'm trying to do a simple conditional with mutate.

The code should create a new variable called "gender" based on two variables from same dataframe.

sample <- data.frame(
   client = c("john", "peter", "hanna", "lisa"), 
   id = c(100, 400,  650, 700),
   resident = c('YES', 'YES', 'YES', 'NO'))

 male_index <- as.vector(000:499)
 female_index <- as.vector(500:999)

 sample <- sample %>%
   mutate(gender = ifelse(resident == "YES" & id %in% male_index, "Male", 
   mutate(gender = ifelse(resident == "YES" & id %in% female_index, "Female", "Female"))))

I'm getting the following error, which I don't understand. I guess it has something to do with SE. But I'm still not that familiar with R.

Error in mutate_impl(.data, dots) :
argument ".data" is missing, with no default

I don't get any issues if I run the code with a single mutate statement.


Solution

  • You don't need the second mutate call in your ifelse.

    sample <- data.frame(
      client = c("john", "peter", "hanna", "lisa"),
      id = c(100, 400,  650, 700),
      resident = c('YES', 'YES', 'YES', 'NO')
    )
    
    male_index <- as.vector(000:499)
    female_index <- as.vector(500:999)
    
    sample <- sample %>%
      mutate(gender = ifelse(
        resident == "YES" & id %in% male_index,
        "Male",
        ifelse(resident == "YES" &
                 id %in% female_index, "Female", "Non-resident")
      ))
    

    Now each individual in the dataset has an assigned value for gender.

    sample
    #  client  id resident gender
    #1   john 100      YES   Male
    #2  peter 400      YES   Male
    #3  hanna 650      YES Female
    #4   lisa 700       NO Non-resident