多个ifelse构建一个额外的向量以添加为列

时间:2017-09-06 13:23:51

标签: r if-statement dataframe

我写了一个函数来检查data.frame的每一行。检查是条件语句,打印是或否。应该很直接。但不知何故,结果并非如预期的那样。我尝试了两种不同的方式。

请在此处找到一些测试数据:TEST TABLE

add_accepted_column <- function(df){
  shopmanager_status <- df[28]
  source_medium <- df[22]
  campaign <- df[23]
  click_to_conversion <- df[29]
  accepted <- c()
  if(shopmanager_status %in% c("complete","processing") & source_medium %in% c("tradetracker / nl", "google / organic", "bing / organic", "yahoo / organic")){
      accepted <- c(accepted,"YES")
  }
  else if(shopmanager_status %in% c("complete","processing") & click_to_conversion < 1){
    accepted <- c(accepted,"YES")
  } 
  else if(shopmanager_status %in% c("complete","processing") & campaign %in% c("1.Top-Brand")){
    accepted <- c(accepted,"YES")
  } else{
    accepted <- c(accepted,"NO")
  }
}

# 
 add_accepted_column <- function(df){
   shopmanager_status <- df[28]
   source_medium <- df[22]
   campaign <- df[23]
   click_to_conversion <- df[29]
   #print(class(click_to_conversion))
   accepted <- c()
   accepted <- c(accepted,if_else(shopmanager_status %in% c("complete","processing") &
                   source_medium %in% c("tradetracker / nl", "google / organic", "bing / organic", "yahoo / organic") ||
                     click_to_conversion < 1 ||
                     campaign %in% c("1.Top-Brand"),"YES","NO"))
   return(accepted)
 }

例如google / cpc给我一个YES是非常奇怪的。

我想申请的实际规则:

•IF shopmanager_status IN(“完成”,“处理”)和IF(source_medium IN(“tradetracker / nl”,“google / organic”,“bing / organic”,“yahoo / organic”) - &gt;是

•IF shopmanager_status IN(“完成”,“处理”)和IF(click_to_conversion&lt; 1) - &gt;是

•IF shopmanager_status IN(“完成”,“处理AND(广告系列IN(”1.顶级品牌“) - &gt;是

•REST - &gt; NO

如果需要更多例子我很乐意供应。不知何故,我无法找出IF ELSE声明的内容。

1 个答案:

答案 0 :(得分:2)

尝试

df$accepted <- df$shopmanager_transaction_status %in% c("complete","processing") &
  (df$sourceMedium %in% c("tradetracker / nl", "google / organic", 
                          "bing / organic", "yahoo / organic") | 
   df$click_to_conversion_date < 1 | df$campaign == "1.Top-Brand")