jeudi 12 novembre 2020

IF(AND formula using R

I need to mutate an additional column that says:

If 'unit price' = 0 and cost > 0, return cost * 1.2. If those conditions are not met, then return 'unit price'.

I've tried the following script and I don't understand what is wrong with it:

df %>%
  group_by(unitprice, cost) %>%
  mutate(unitprice3 = if_else(unitprice == 0 && cost > 0, cost * 1.2, unitprice))

I get the following error:

Error: Problem with `mutate()` input `unitprice3`.
x object 'unitprice3' not found
ℹ Input `unitprice3` is `if_else(unitprice == 0 && cost > 0, cost * 1.2, unitprice3)`.
ℹ The error occurred in group 1: unitprice = 0, cost = 1.7.

This is the data I'm working with:

structure(list(customer = c("John", "Atticus", "Sally", "Bridget", 
"John", "Atticus", "Bridget", "Atticus", "Crystal", "Henry"), 
    unitprice = c(2, 0, 1, 0, 4, 5, 2, 3, 7, 6), item = c("x", 
    "x", "y", "y", "y", "y", "y", "x", "x", "x"), unitprice2 = c(2, 
    3, 1, 2, 4, 5, 2, 3, 7, 6), cost = c(1.7, 2.55, 0.85, 1.7, 
    3.4, 4.25, 1.7, 2.55, 5.95, 5.1)), row.names = c(NA, -10L
), groups = structure(list(unitprice2 = c(1, 2, 3, 4, 5, 6, 7
), .rows = structure(list(3L, c(1L, 4L, 7L), c(2L, 8L), 5L, 6L, 
    10L, 9L), ptype = integer(0), class = c("vctrs_list_of", 
"vctrs_vctr", "list"))), row.names = c(NA, 7L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

# A tibble: 10 x 5
# Groups:   unitprice2 [7]
   customer unitprice item  unitprice2  cost
   <chr>        <dbl> <chr>      <dbl> <dbl>
 1 John             2 x              2  1.7 
 2 Atticus          0 x              3  2.55
 3 Sally            1 y              1  0.85
 4 Bridget          0 y              2  1.7 
 5 John             4 y              4  3.4 
 6 Atticus          5 y              5  4.25
 7 Bridget          2 y              2  1.7 
 8 Atticus          3 x              3  2.55
 9 Crystal          7 x              7  5.95
10 Henry            6 x              6  5.1 

And this is the desired output in the new column:

[1] 2.00 3.06 1.00 2.04 4.00 5.00 2.00 3.00 7.00 6.00

Thank you for your help

Aucun commentaire:

Enregistrer un commentaire