簡體   English   中英

如何將包括布爾運算符在內的多個條件應用於 ifelse 語句

[英]How to apply multiple conditions including Boolean operators to an ifelse statement

我需要一點幫助。 我想創建一個簡單的代碼而不是放入多行代碼以獲得相同的結果

Discount <- NewORdersData %>%
     mutate(Discount = ifelse(Coupon == "OFF10" | "LARGE10", Sub_Total * 0.1, Sub_total * 0.05, Coupon))

我收到一條錯誤消息 - ifelse(Coupon == "OFF10" | "LARGE10", Sub_Total * 0.1, Sub_total * 中的錯誤:未使用的參數(優惠券)

  1. 我想在我的數據框中創建一個新列(折扣)
  2. 如果優惠券列中的值顯示為 OFF10 或 LARGE10 - 應用 10% 的折扣,即(小計 *10%) 如果優惠券列中的值顯示為 OFF5 - 應用 5% 的折扣,即 (Sub_Total *10%)
dput(NewORdersData[1:10, "Coupon", drop = FALSE])
structure(list(Coupon = c("OFF10", NA, "LARGE10", "LARGE10", 
"LARGE10", "OFF10", "LARGE10", "LARGE10", NA, "LARGE10")), row.names = c(NA, 
10L), class = "data.frame")

dput(NewORdersData[1:10, "Sub_Total", drop = FALSE])
structure(list(Sub_Total = c(27.98, 28.9, 74.94, 91.85, 80.82, 
37.85, 48.8, 102.8, 12.95, 46.92)), row.names = c(NA, 10L), class = "data.frame")

試試這個更新的代碼

 NewORdersData %>%
 mutate(Discount = case_when(Coupon %in% c("OFF10", "LARGE10") ~ 0.1, Coupon == "OFF5" ~ 0.05, TRUE ~ 0) * Sub_Total)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM