2014-12-03 53 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