'Adding a new column in a Dataframe based on two conditions from two different columns in dplyr

I have a data.frame containing two rows: car is a model of car and num is the number of cars of that model that I have observed in a car park.

Using dplyr::mutate(), I want add another column, pop_car (popular cars), which repeats the car brand name if it has num > 1 and shows "Other" if num = 1.

car <- c("Audi", "Toyota", "Nissan", "Ford", "Hyundai", "Mercedes")
num <- c(5,3,1,4,4,1)
 
df <- data.frame(car, num)

df

#         car num  
# 1      Audi   5    
# 2    Toyota   3    
# 3    Nissan   1    
# 4      Ford   4    
# 5   Hyundai   4    
# 6  Mercedes   1    

I'm trying to write code to get the dataframe to look like this:

 car     num  pop_car
Audi      5    Audi
Toyota    3    Toyota
Nissan    1    Other  
Ford      4    Ford
Hyundai   4    Hyundai
Mercedes  1    Other

so far I've tried

df |>
mutate(pop_car = df$car if num >1) |>
  if_else(pop_car = other if num == 1 )

Also when answering please pretend that this is a much longer data frame, which means avoid writing down the car brands in the function



Solution 1:[1]

require(dplyr)
mutate(df, pop_car = ifelse(num > 1, pop_car, "Other"))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Captain Hat