我有嵌套函数,并希望将参数传递给最深的函数.最深的函数已经有默认参数,所以我将更新这些参数值.
我的mwe正在使用plot(),但实际上我正在png()使用默认的高度和宽度参数.
有什么建议?
f1 <- function(...){ f2(...)}
f2 <- function(...){ f3(...)}
f3 <- function(...){ plot(xlab="hello1", ...)}
#this works
f1(x=1:10,y=rnorm(10),type='b')
# I want to update the default xlab value, but it fails:
f1(x=1:10,y=rnorm(10),type='b', xlab='hello2')
Run Code Online (Sandbox Code Playgroud)
在你的f3(),"hello1"不是xlab函数的形式参数列表中的默认值.它是函数体中提供的值,因此无法覆盖它:
f3 <- function(...){ plot(xlab="hello1", ...)}
Run Code Online (Sandbox Code Playgroud)
我怀疑你的意思是做这样的事情.
f1 <- function(...){ f2(...)}
f2 <- function(...){ f3(...)}
f3 <- function(..., xlab="hello1") plot(..., xlab=xlab)
## Then check that it works
par(mfcol=c(1,2))
f1(x=1:10,y=rnorm(10),type='b')
f1(x=1:10,y=rnorm(10),type='b', xlab='hello2')
Run Code Online (Sandbox Code Playgroud)
(请注意,形式参数xlab 必须遵循...此处的参数,以便它只能完全匹配(而不是部分匹配).否则,在没有命名的参数的情况下xlab,它将被命名的参数匹配x,可能(实际上在这里)给你带来很多悲伤.)