[英]Switch Statement with repeated commands in R
在R中,有沒有辦法制作一個switch語句,以便為兩種不同的情況執行相同的代碼塊? 顯然我可以復制並粘貼兩個語句的整個代碼,但我希望有一個更簡潔的方法來做到這一點。
我也可以使用if-else塊來避免重復大塊代碼,但是在R中切換通常更快。
由於R將switch語句解析為函數的方式似乎不太可能,但我希望R的開發人員特別注意解析switch語句以允許多個參數引用相同的代碼塊。
提供沒有值的命名參數,它們會通過值轉到下一個表達式
> switch("A", A=, B=, C="A OR B OR C", "Other")
[1] "A OR B OR C"
> switch("C", A=, B=, C="A OR B OR C", "Other")
[1] "A OR B OR C"
> switch("D", A=, B=, C="A OR B OR C", "Other")
[1] "Other"
這在幫助頁面?switch
有所描述
If 'EXPR' evaluates to a character string then that string is
matched (exactly)to the names of the elements in '...'. If there
is a match then that element is evaluated unless it is missing, in
which case the next non-missing element is evaluated, so for
example 'switch("cc", a = 1, cc =, cd =, d = 2)' evaluates to '2'.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.