在R中使用多个三点省略号

时间:2017-02-02 16:42:12

标签: r

有没有办法将任意参数传递给函数内的多个命令?以下功能显然不起作用,但我希望它能解释我想要实现的目标。

test = function(x = rnorm(20), y = rnorm(20), ..., ---){
    plot(x, y, type = "p", ...)
    lines(x, y, ---) 
}

目标是能够编写一个创建情节linespoints以及polygon的函数,并且可以为每个命令获取任意参数并将它们传递给相应的命令没有我必须为每个命令显式指定参数。

2 个答案:

答案 0 :(得分:3)

这是一种黑客行为:

.. <- "/////" #or anything which won't be used as a valid parameter

f <- function(...){
  arguments <- list(...)
  if(.. %in% arguments){
    i <- which(arguments == ..)
    terms <- unlist(arguments[1:(i-1)])
    factors <- unlist(arguments[(i+1):length(arguments)])
    c(sum(terms),prod(factors))
  }
}

然后,例如,

> f(2,3,4,..,7,8,10)
[1]   9 560

您显然可以将该想法扩展到多个...字段,每个字段都以..

分隔

答案 1 :(得分:1)

选项1

<强>功能

test = function(x = rnorm(20), y = rnorm(20), plot_options = NA, ...){
    if (is.na(plot_options) == FALSE){
        eval(parse(text = paste0("plot(x, y, ", plot_options, ")")))
    } else {
        plot(x, y, type = "n")
    }
    lines(x, y, ...) 
}

<强> USAGE

test()

enter image description here

set.seed(42)
m = rnorm(20)
n = rnorm(20)
test(x = m, y = n,
    plot_options = "type = 'p', col = 'red', pch = 19, xlab = 'Test Plot', ylab = 'Y-axis'")

enter image description here

选项2(@Gregor&#39}解决方案)

<强>功能

test2 = function(x = rnorm(20), y = rnorm(20), ..., line_options){
    plot(x, y, ...)
    if (missing(line_options)) { 
        lines(x, y) 
    } else { 
        do.call(lines, c(list(x = x, y = y), line_options))
    }
}

<强> USAGE

par(mfrow = c(2, 2), mar = c(2, 2, 1, 1))
test2(main = 'default')
test2(line_options = list(lty = 2), main = 'line')
test2(col = 'red', main = 'plot')
test2(col = 'red', line_options = list(lty = 2, col = 'blue'), main = 'line and plot')

enter image description here