IF(AND公式使用R

时间:2020-11-12 13:17:42

标签: r if-statement

我需要对另一列进行修改:

如果“单价” = 0且成本> 0,则退货成本* 1.2。如果不满足这些条件,则返回“单价”。

我尝试了以下脚本,但我不明白该怎么办:

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

我收到以下错误:

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.

这是我正在使用的数据:

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 

这是新列中所需的输出:

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

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

&而不是&&用于矢量(我个人总是使用&)。

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

# A tibble: 10 x 6
# Groups:   unitprice, cost [9]
   customer unitprice item  unitprice2  cost unitprice3
   <chr>        <dbl> <chr>      <dbl> <dbl>      <dbl>
 1 John             2 x              2  1.7        2   
 2 Atticus          0 x              3  2.55       3.06