Home > OS >  How to replace values in a column for a specific condition?
How to replace values in a column for a specific condition?

Time:12-19

I want to change the orders to 100 if my revenues > 1900 and the day is not "sun" Can someone please help. Any help will be appreciated.

my data:

df1 <- structure(list(day = c("mon", "tue", "wed", "thu", "fri", "sat", 
"sun"), orders = c(90L, 80L, 50L, 20L, 5L, 20L, 95L), revenues = c(1800L, 
2000L, 1000L, 2000L, 100L, 400L, 1900L)), class = "data.frame", row.names = c("Day1", 
"Day2", "Day3", "Day4", "Day5", "Day6", "Day7"))

CodePudding user response:

Create a logical vector and use that index to do the assignment

i1 <- with(df1, day != 'sun' & revenues > 1900)
df1$orders[i1] <- 100

-output

> df1
     day orders revenues
Day1 mon     90     1800
Day2 tue    100     2000
Day3 wed     50     1000
Day4 thu    100     2000
Day5 fri      5      100
Day6 sat     20      400
Day7 sun     95     1900

CodePudding user response:

library(dplyr)

df %>% 
  mutate(orders = ifelse(revenues > 1900 & day != "sun", 100, orders))

     day orders revenues
Day1 mon     90     1800
Day2 tue    100     2000
Day3 wed     50     1000
Day4 thu    100     2000
Day5 fri      5      100
Day6 sat     20      400
Day7 sun     95     1900
  •  Tags:  
  • r
  • Related