基于多个列标准创建条件列(R)

时间:2018-06-01 19:57:57

标签: r if-statement

TowQty <- c(2,3,4,5,9,0,0,0,4);
SvcQty<- c(4,8,3,4,2,0,,4,0,2);
Acc.AvgTowInv<- c(20,25,65,45,67,0,0,0,76);
Acc.AvgSvcInv<-c(25,32,45,53,23,0,26,0,43)

data.frame <- data.frame(TowQty , SvcQty, Acc.AvgTowInv, Acc.AvgSvcInv, stringsAsFactors=FALSE)

?根据以下条件创建新的Conditional_Column

当(TowQty&gt; 0和SvcQty&gt; 0)然后(((1 - ((Acc.AvgTowInv - 50.0)/ 50.0))* 40)+((1 - ((Acc.AvgSvcInv - 25.0)/ 25.0))* 40))/ 2
当(TowQty> 0和SvcQty = 0)然后((1 - ((Acc.AvgTowInv - 50.0)/ 50.0))* 40)
当(TowQty = 0且SvcQty> 0)然后((1 - ((Acc.AvgSvcInv - 25.0)/ 25.0))* 40)
when(TowQty = 0且SvcQty = 0)则为0

想要R编程语言中的解决方案。谢谢!

2 个答案:

答案 0 :(得分:0)

您可以编写一系列ifelse语句,如下所示:

a <- c(1,2,0,0)
b <- c(3,0,2,0)
c <- c(0,10,11,12)
d <- c(0,11,12,13)

data.frame <- data.frame(a , b, c, d, stringsAsFactors=FALSE)

data.frame$nc <- with(data.frame, 
                  ifelse(a > 0 & b >0, c+3, 
                         ifelse(a > 0 & b==0, c+4,
                                ifelse(a==0 & b>0, c+5,
                                       ifelse(a==0 & b==0, 0, 0))))) 

data.frame

  a b  c  d nc
1 1 3  0  0  3
2 2 0 10 11 14
3 0 2 11 12 16
4 0 0 12 13  0

答案 1 :(得分:0)

您可以使用ifelse,而不是使用嵌套的dplyr::case_when()

require(tidyverse)

TowQty <- c(2,3,4,5,9,0,0,0,4)
SvcQty<- c(4,8,3,4,2,0,4,0,2)
Acc.AvgTowInv<- c(20,25,65,45,67,0,0,0,76)
Acc.AvgSvcInv<-c(25,32,45,53,23,0,26,0,43)

data.frame <- data.frame(TowQty , SvcQty, Acc.AvgTowInv, 
                         Acc.AvgSvcInv, stringsAsFactors=FALSE)

data.frame %>% 
  mutate(newCalc = case_when(
    #Con. 1.
    TowQty > 0 & SvcQty > 0  ~ 
      (((1 - ((Acc.AvgTowInv - 50) / 50)) * 40) +
         ((1 - ((Acc.AvgSvcInv - 25) / 25.0)) * 40)) / 2, 
    #Con. 2
    TowQty > 0 & SvcQty == 0 ~ 
      (1 - ((Acc.AvgTowInv - 50) / 50)) * 40, 
    #Con. 3
    TowQty == 0 & SvcQty > 0 ~ (1 - ((Acc.AvgSvcInv - 25) / 25)) * 40, 
    #Con. 4 
    TowQty == 0 & SvcQty == 0 ~ 0 ))