Conditional Mutate - Make negative values zero

Good day,

Suppose that I have this dataset containing the information on cost &revenue of multiple stores and it looks something like this:

Region Store Revenue Cost
A Store 1 64 23
B Store 2 72 26
B Store 3 52 19
A Store 4 41 45

or

Cost_Revenue_Data = data.frame(Region= c('A', 'B', 'B', 'A'),
                     Store = c('Store 1', 'Store 2', 'Store 3', 'Store 4'),
                     Revenue = c(64, 72, 52, 41),
                     Cost = c(23, 26, 19, 45))
                     

I am using mutate function to estimate the profit (Revenue - Cost = Profit) of each store:

Profit_Data <- Cost_Revenue_Data  %>% mutate(Profit = Revenue - Cost)

But I wanna make Profit = 0 if it's negative. So the final table should look like this:

Region Store Revenue Cost Profit
A Store 1 64 23 41
B Store 2 72 26 46
B Store 3 52 19 33
A Store 4 41 45 0

Basically if Revenue - Cost = Profit < 0, I wanna make it equal zero instead of having negative values. Anybody know how to do this?

Try this:

Profit_Data <- Cost_Revenue_Data  %>% 
  mutate(Profit = ifelse(Revenue - Cost < 0, 0, Revenue - Cost))

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.