我無法完全理解您想如何構建if語句,但以下內容可以基於上一列中的信息添加新列。
Source <- c("A", "B", "C", "D", "E")
Rev_Diff <- c(-10, 11, 12, 11, 10)
Cost_Diff <- c(10, -10, 10, -11, 11)
Price_Diff <- c(-11, 10, -10, 10, 10)
Sales_Diff <- c(12, 11, 11, -12, 11)
df <- data.frame(Source, Rev_Diff, Cost_Diff, Price_Diff, Sales_Diff)
df %>%
mutate(ReasonDown = ifelse(Rev_Diff < 0, paste("Rev", Rev_Diff),
ifelse(Cost_Diff < 0, paste("Cost", Cost_Diff),
ifelse(Price_Diff < 0, paste("Price", Price_Diff),
ifelse(Sales_Diff < 0, paste("Sales", Sales_Diff), "We're up")))))
Source Rev_Diff Cost_Diff Price_Diff Sales_Diff ReasonDown
1 A -10 10 -11 12 Rev -10
2 B 11 -10 10 11 Cost -10
3 C 12 10 -10 11 Price -10
4 D 11 -11 10 -12 Cost -11
5 E 10 11 10 11 We're up
然而,ifelse將停止一旦找到一個真實的陳述,所以這不會是能夠打印出多個「下來的原因」就像你在源D.有如果你真的想要打印的一切,我覺得您應該可以添加4個新列以檢查Rev,Cost,Price,Sales中的每個列,並添加第5列來總結所有內容。
df %>%
mutate(RRev = ifelse(Rev_Diff < 0, paste("Rev", Rev_Diff), "")) %>%
mutate(RCost = ifelse(Cost_Diff < 0, paste("Cost", Cost_Diff), "")) %>%
mutate(RPrice = ifelse(Price_Diff < 0, paste("Price", Rev_Diff), "")) %>%
mutate(RSales = ifelse(Sales_Diff < 0, paste("Sales", Rev_Diff), "")) %>%
mutate(DownReason = ifelse(nchar(paste(RRev, RCost, RPrice, RSales)) > 3, paste(RRev, RCost, RPrice, RSales), "We're UP"))
Source Rev_Diff Cost_Diff Price_Diff Sales_Diff RRev RCost RPrice RSales DownReason
1 A -10 10 -11 12 Rev -10 Price -10 Rev -10 Price -10
2 B 11 -10 10 11 Cost -10 Cost -10
3 C 12 10 -10 11 Price 12 Price 12
4 D 11 -11 10 -12 Cost -11 Sales 11 Cost -11 Sales 11
5 E 10 11 10 11 We're UP
也許用'max.col'下回考慮做一個不太複雜的例子(如,沒有「轉」點「成本」等) – Frank