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
しかし、私が思うに、それはTRUE文を見つけたら、ifelseは停止しますので、あなたがソースD.に持っていたようにあなたが本当にすべてを印刷したい場合、これは、複数の「ダウンの理由を」プリントアウトすることができませんRev、Cost、Price、Salesのそれぞれをチェックする4つの新しい列を追加し、すべてを要約するために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
たぶん – Frank