2012-05-01 35 views
57

我想用我的函數R語句switch()根據函數參數的值觸發不同的計算。如何在R函數中使用switch語句?

例如,在Matlab你可以做到這一點通過寫

switch(AA)   
case '1' 
... 
case '2' 
... 
case '3' 
... 
end 

我發現這個職位 - switch() statement usage - 解釋如何使用switch,但不是真的對我很有幫助,因爲我要執行更復雜的計算(矩陣運算)而不是簡單的mean

回答

75

好,switch可能不是真正的意思是這樣的工作,但你可以:

AA = 'foo' 
switch(AA, 
foo={ 
    # case 'foo' here... 
    print('foo') 
}, 
bar={ 
    # case 'bar' here... 
    print('bar')  
}, 
{ 
    print('default') 
} 
) 

...每一種情況下是一種表達 - 通常只是一個簡單的事情,但在這裏我用捲曲 - 阻止,以便你可以填充任何你想要的代碼在那裏...

+4

是有辦法做到這一點沒有比較字符串?這似乎廣泛低效。 – Julius

30

我希望這個例子有所幫助。你可以使用花括號來確保你已經把所有的東西都放在切換器變換器中(抱歉,不知道技術術語,但是在=號之前的術語會改變發生的事情)。我認爲開關是一種更受控制的if() {} else {}陳述。

每次開關功能相同,但我們提供的命令發生變化。

do.this <- "T1" 

switch(do.this, 
    T1={X <- t(mtcars) 
     colSums(mtcars)%*%X 
    }, 
    T2={X <- colMeans(mtcars) 
     outer(X, X) 
    }, 
    stop("Enter something that switches me!") 
) 
######################################################### 
do.this <- "T2" 

switch(do.this, 
    T1={X <- t(mtcars) 
     colSums(mtcars)%*%X 
    }, 
    T2={X <- colMeans(mtcars) 
     outer(X, X) 
    }, 
    stop("Enter something that switches me!") 
) 
######################################################## 
do.this <- "T3" 

switch(do.this, 
    T1={X <- t(mtcars) 
     colSums(mtcars)%*%X 
    }, 
    T2={X <- colMeans(mtcars) 
     outer(X, X) 
    }, 
    stop("Enter something that switches me!") 
) 

這是一個函數內部:

FUN <- function(df, do.this){ 
    switch(do.this, 
     T1={X <- t(df) 
      P <- colSums(df)%*%X 
     }, 
     T2={X <- colMeans(df) 
      P <- outer(X, X) 
     }, 
     stop("Enter something that switches me!") 
    ) 
    return(P) 
} 

FUN(mtcars, "T1") 
FUN(mtcars, "T2") 
FUN(mtcars, "T3") 
26

開關的那些不同的方式...

# by index 
switch(1, "one", "two") 
## [1] "one" 


# by index with complex expressions 
switch(2, {"one"}, {"two"}) 
## [1] "two" 


# by index with complex named expression 
switch(1, foo={"one"}, bar={"two"}) 
## [1] "one" 


# by name with complex named expression 
switch("bar", foo={"one"}, bar={"two"}) 
## [1] "two"