[英]If statement with 9 else conditions in R
我有一個函數,它研究9種不同的可能性,並據此選擇一種具有以下形式的動作:
我正在做的是查找向量,並為向量中的每個條目確定
IF the value in the vector is 1 THEN start function B
IF the value in the vector is 2 THEN start function C
IF the value in the vector is 3 THEN start function D
IF the value in the vector is 4 THEN start function E
等等
我想在R中寫這個。是否只為每個案例加上“ else”?
我已經嘗試通過以下方式進行switch
:
condition<-6
FUN<-function(condition){
switch(condition,
1 = random1(net)
2 = random2(net)
3 = random3(net)
4 = random4(net)
5 = random5(net)
6 = random6(net)
7 = random7(net)
8 = random8(net)
9 = random9(net)
10= random10(net))
}
其中隨機數1到10是使用變量'net'的函數
並且switch
命令試圖執行的操作是檢查'condition'的值,並且是否如上例中的6那樣運行函數: random6(net)
這兩個答案都為您提供了正確的工具,但這是恕我直言,應該如何編寫。 到目前為止,OP和這兩種解決方案都在創建使用全局變量( net
)的函數,這不是最佳實踐。
假設randomX
是一個參數net
函數,即:
random1 <- function(net){ [...] }
random2 <- function(net){ [...] }
[etc.]
然后,您需要執行以下操作:
FUN <- switch(condition,
'1' = random1,
'2' = random2,
[etc.])
或更好:
FUN.list <- list(random1, random2, [etc.])
FUN <- FUN.list[[condition]]
在這兩種情況下,輸出都是一個將net
作為輸入的函數(就像randomX
一樣),因此您可以通過執行以下操作對其進行評估:
FUN(net)
還要注意,您可以使用第二種方法一口氣完成所有操作:
FUN.list[[condition]](net)
另一個解決方案是將要調用的所有函數打包到一個列表randoms
,然后根據condition
選擇一個列表項:
randoms <- list(random1, random2, random3, random4, random5, random6, random7, random8, random9, random10)
FUN <- function(condition) {
randoms[[condition]](net)
}
使用switch
功能,如下所示:
foo <- function(condition){
switch(condition,
'1' = print('B'),
'2' = print('C'),
'3' = print('D'),
'4' = print('E'))
}
> foo(1)
[1] "B"
> foo(2)
[1] "C"
> foo(3)
[1] "D"
> foo(4)
[1] "E"
更多詳細信息在?switch
根據您的示例:
condition<-6
FUN<-function(condition){
switch(condition,
'1' = random1(net), # Maybe you're missing some commas here
'2' = random2(net), # and here
'3' = random3(net), # and here
'4' = random4(net)
....) # all the way to '10' = random10(net)
}
這將達到目的
這對我來說很好:
Foo <- function(condition){
x <- 1:20
switch(condition,
'1' = mean(x),
'2' = var(x),
'3' = sd(x))
}
> Foo(1)
[1] 10.5
> Foo(2)
[1] 35
> Foo(3)
[1] 5.91608
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.