2016-11-18 62 views
1

在使用QCA軟件包時,我們通常採用ifelse來將數據集列替換爲二分值。但是我發現在處理模糊集合時必須使用嵌套的ifelse s是很難看的。在處理載體時取代ifelse的案例陳述

有沒有辦法使用case語句呢? switch僅用於控制流程,並不處理向量。

例如:

DDDfz $VIES <- ifelse (DDD $vies == "p", 1, 0) 

是確定的,但

DDDfz $TIPO <- switch (DDD $tipo, "PD", 0, "PL", 0.5, "MP", 1) 
    Error in switch(DDD$tipo, "PD", 0, "PL", 0.5, "MP", 1) : 
    EXPR deve ser um vetor de comprimento 1 

回答

4

switch沒有矢量化,不能在這裏使用。 R爲這樣的任務提供factor數據類。

factor(c(0, 0.5, 1), levels = c(0, 0.5, 1), 
        labels = c("PD", "PL", "MP")) 
#[1] PD PL MP 
#Levels: PD PL MP 

在第一個例子中,您也不需要ifelse。你可以簡單地做as.integer(DDD$vies == "p")

PS:在$前面的空格是一種奇怪的代碼風格。

1
#data example 
TIPO = c("PD", "PL", "MP", "PL", "MP") 

# here we create dictionary 
dict = c("PD" = 0, "PL" = 0.5, "MP" = 1) 
# further we match dictionary with original values 
recoded_TIPO = dict[TIPO] 

# result 
recoded_TIPO 
0

該R switch功能不幸的是相當有限的用處。 The ‹dplyr› package has a nice pattern matching function這是更強大的:

result = case_when(
    x == 'PD' ~ 0, 
    x == 'PL' ~ 0.5, 
    x == 'MP' ~ 1 
) 

在此特定情況下,其它的解決方案(使用因子或載體)是更簡潔,也更有效率。但case_when一般來說更強大。