2012-03-29 18 views
2

我還是新的寫作功能R.要麼/或論點

我嘗試寫,需要一個功能: 無論是參數「一」,或參數「B」和「C 「在一起。

此外,此函數有一些參數與默認值。

如何最好地處理任一個/或 - 參數。如果提供「a」 我不需要「b」和「c」,反之亦然,但至少需要一個。

此外,「a」是一個字符串(水果像「蘋果」,「梨」等),而「b」和「c」是值。在背景中有數據框,其中每個水果的值「b」和「c」被定義。因此,使用該函數可能需要一個有效果(參數「a」)或值「b」和「c」本身。

我開始用的功能:

f <- function(a,b,c,d=1,e=2) 
+2

也許最簡單的方法就是折騰一些'if(missing(a)){if(missing(b)|缺少(c))[做一些有用的]}代碼到你的函數的開頭。重要的注意事項:避免使用「c」作爲變量名稱,因爲它與內建的'c()'函數衝突。 – 2012-03-29 13:20:03

回答

3
dfrm <- data.frame(a=LETTERS[1:3], 
     b=letters[1:3], 
     c=letters[5:7], 
     res=c("one", "two", "three")) 
dfrm 
# 
    a b c res 
1 A a e one 
2 B b f two 
3 C c g three 

f <- function(a=NA,b=NA,c=NA,d=1,e=2){ 
       if(is.na(a) & (is.na(b) | is.na(c))) {stop()} 
       if (!is.na(a)) {dfrm[dfrm[[1]]==a, ]} else { 
           dfrm[dfrm[[2]]==b & dfrm[[3]] == c , ] } 
} 
f("A") 
# 
    a b c res 
1 A a e one 

f(b="a", c="e") 
# 
    a b c res 
1 A a e one 

f() 
#Error in f() : 
1

missing功能應該幫助:

f <- function(a,b,c,d=1,e=2) { 
    if (missing(a)) { 
     # use b and c 
     b+C# you'll get an error here if b or c wasn't specified 
    } else { 
     # use a 
     nchar(a) 
    } 
} 

f('foo') # 3 
f(b=2, c=4) # 6 
f(d=3)  # Error in b + c : 'b' is missing 
+0

@CarlWitthoft - 不,'nchar(a)'只有在'a'不*丟失時纔會執行。 – Tommy 2012-03-29 17:55:02

+0

是的,對於誤讀抱歉。 – 2012-03-29 21:18:17