2014-12-03 34 views
1

我在R中創建一個函數,我要求一個字母(或一個字符串)。這裏是第一個函數的一個例子:使用字符R函數

fun.1<-function(a=2,b=3,c=4) return(a+b^2+c^3) 

和使用的第一個另一個功能:

fun.2<-function(letter.to.test="a",a=2,b=3,c=4){ 
    if(letter.to.test=="a") {a=0:10} 
    else if(letter.to.test=="b"){b=0:10} 
    else {c=0:10} 
    return(fun.1(a,b,c)) 
} 

我怎麼可能寫fun.2沒有的if else功能?在我的真實代碼中,我有46個參數可供測試,所以如果還有其他問題,請寫46。謝謝

+0

你已經有了一個很好的答案,但一般性評論:spacesinyourcodemakeitaloteasiertoread。 – Gregor 2014-12-03 17:06:00

回答

1

更通用的方法:

fun.2 <- function(letter.to.test="a", a=2, b=3, c=4) { 
    if (letter.to.test %in% letters[1:3]) { 
     assign(letter.to.test, 1:10) 
     fun.1(a,b,c) 
    } 
} 
+0

所有的答案都是有用的,但我正在尋找的函數是'assign()'。並且還要感謝'%in%'中的*檢查功能。 – 2014-12-03 17:41:13

+1

這幾乎是「一般」。但是,在'%in%'中使用'args'或'formals'的參數名稱。 – 2014-12-03 18:11:23

0

你想要一個switch聲明。

fun.2<-function(letter.to.test="a",a=2,b=3,c=4){ 
    switch(letter.to.test, 
     a = {a=0:10}, 
     b = {b=0:10}, 
     c = c=0:10} 
    ) 
    return(fun.1(a,b,c)) 
} 
+0

OP將仍然必須在開關 – rawr 2014-12-03 17:38:04

+0

@rawr中寫46個表達式我假設表達式可能在字母之間不同。你是正確的,仍然需要46個表達式。 – cdeterman 2014-12-03 17:39:47

0

如果你希望它們都分配到相同的值(例如,0:10),試試這個:

fun.2<-function(letter.to.test="a",a=2,b=3,c=4){ 
    assign(paste(parse(text = letter.to.test)), 0:10) 
    return(fun.1(a,b,c)) 
} 
1

你可以替換test的值爲call<-。然後評估它來更改值。

fun.2 <- function(test = "a", a = 2, b = 3, c = 4) { 
    eval(call("<-", as.name(substitute(test)), 0:10)) 
    fun.1(a, b, c) 
} 

fun.2() 
# [1] 73 74 75 76 77 78 79 80 81 82 83 
1

你不需要fun.2

fun.1<-function(a=2,b=3,c=4) return(a+b^2+c^3) 

mapply(fun.1, a=1:10, SIMPLIFY = TRUE) 
# [1] 74 75 76 77 78 79 80 81 82 83 

mapply(fun.1, b=1:10, SIMPLIFY = TRUE) 
# [1] 67 70 75 82 91 102 115 130 147 166 
+0

謝謝。實際上,這是一個使用我創建的3個函數的46個參數的函數示例。但也許,我應該嘗試'mapply()'。 – 2014-12-03 17:49:38