2017-09-13 236 views
0

我有2個變量promo_freq和disc_freq。根據這兩個變量的值,我想創建第三個變量promo_segmnt。然而,R中嵌套的ifelse並沒有發揮作用,我得到的第三個變量的唯一值是「NA」。根據我的數據,這不能是輸出。 請找到下面提到的代碼。 在此先感謝。嵌套ifelse在R

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

你能提供樣品的輸入和預期的輸出? –

回答

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。

+0

謝謝一個男人!有效。多餘空間出現問題。使用您提供的邏輯刪除它。現在我的程序工作正常:) –

1

如果你正在尋找一個替代使用if_else,那麼你可以做到這一點是使用case_whendplyr包:

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