在R中嵌套ifelse

时间:2017-09-13 05:34:54

标签: r if-statement

我有2个变量promo_freq和disc_freq。根据这两个变量的值,我想创建第3个变量promo_segmnt。然而,R中的嵌套ifelse看起来没有用,我得到的第三个变量的唯一值是" NA"。根据我的数据,这不一定是输出。 请找到下面提到的代码。 提前谢谢。

Promotion1$promo_segmnt <-ifelse(Promotion1$disc_freq == "1.Low_disc" & Promotion1$promo_freq == "1.Low_promo","1.Low",
ifelse(Promotion1$disc_freq == "2.Med_disc" & Promotion1$promo_freq == "3.High_promo","3.High",
ifelse(Promotion1$disc_freq == "3.High_disc" & Promotion1$promo_freq == "3.High_promo","3.High ","NA")))

2 个答案:

答案 0 :(得分:2)

正常情况对我有用。

disc_freq <- c("1.Low_disc", "2.Med_disc", "3.High_disc", "4.na")
promo_freq <- c("1.Low_promo", "3.High_promo", "3.High_promo", "4.na")
Promotion1 <- data.frame(disc_freq, promo_freq)

<强> Promotion1

disc_freq    promo_freq
<fctr>       <fctr> 
1.Low_disc  1.Low_promo         
2.Med_disc  3.High_promo            
3.High_disc 3.High_promo            
4.na    4.na


Promotion1$promo_segmnt <-
  ifelse(
  (Promotion1$disc_freq == "1.Low_disc") &
  (Promotion1$promo_freq == "1.Low_promo"),
  "1.Low",
  ifelse(
  (Promotion1$disc_freq == "2.Med_disc") &
  (Promotion1$promo_freq == "3.High_promo"),
  "3.High",
  ifelse(
  (Promotion1$disc_freq == "3.High_disc") &
  (Promotion1$promo_freq == "3.High_promo"),
  "3.High ",
  "NA"
  )
  )
  )

[1] "1.Low"   "3.High"  "3.High " "NA"

您的列中可能有一些额外的空格。你可以使用stringr包删除它。

library(stringr)

Promotion1 $disc_freq<- str_trim(Promotion1 $disc_freq, side = "both")
Promotion1 $promo_freq<- str_trim(Promotion1 $promo_freq, side = "both")
然后再尝试ifelse。

答案 1 :(得分:2)

如果您正在寻找使用if_else的替代方法,那么您可以使用case_when包中的dplyr

suppressPackageStartupMessages(library(tidyverse)) 

disc_freq <- c("1.Low_disc", "2.Med_disc", "3.High_disc", "4.na")
promo_freq <- c("1.Low_promo", "3.High_promo", "3.High_promo", "4.na")
Promotion1 <- data.frame(disc_freq, promo_freq)

mutate(Promotion1, promo_segmnt = case_when(
  disc_freq == "1.Low_disc" & promo_freq == "1.Low_promo" ~"1.Low",
  disc_freq == "2.Med_disc" & promo_freq == "3.High_promo" ~"3.High",
  disc_freq == "3.High_disc" & promo_freq == "3.High_promo" ~"3.High",
  TRUE ~"NA"))

#>     disc_freq   promo_freq promo_segmnt
#> 1  1.Low_disc  1.Low_promo        1.Low
#> 2  2.Med_disc 3.High_promo       3.High
#> 3 3.High_disc 3.High_promo       3.High
#> 4        4.na         4.na           NA