Home > other >  Changing parametres in a function call in R
Changing parametres in a function call in R

Time:01-17

I wrote a function drawing circles. Lines are type ‘solid’ and color is black by default. However, I want they could be changed in a function call. Is it possible?

my_func <- function(vector, ...) {
  len <- length(vector)
  m <- max(vector)
# plot
  plot(1, type="n", xlab="", ylab="", xlim=1.2*m*c(-1,1), ylim=1.2*m*c(-1,1), asp = 1)
  circle <- seq(0, 2*pi   0.1, 0.1)
  sapply(vector, function(x) lines(x*cos(circle), x*sin(circle)))
}

dd <- 1:4
my_func(dd, lines(col = "red", lty="dashed"))

CodePudding user response:

You could just pass the extra arguments to the function:

my_func <- function(vector, col='black',lty='solid') {
  len <- length(vector)
  m <- max(vector)
  # plot
  plot(1, type="n", xlab="", ylab="", xlim=1.2*m*c(-1,1), ylim=1.2*m*c(-1,1), asp = 1)
  circle <- seq(0, 2*pi   0.1, 0.1)
  sapply(vector, function(x) lines(x*cos(circle), x*sin(circle),col=col,lty=lty))
}

dd <- 1:4
my_func(dd,'red','dashed')

enter image description here

CodePudding user response:

The way suggested by Waldi will work for those two parameters. However, you will have to add each parameter that you wish to pass manually.

Alternatively, use do.call to pass the ... to the required function - meaning you will be able to pass any of the parameters accepted by lines:

my_func2 <- function(vector, ...) {
    len <- length(vector)
    m <- max(vector)
    # plot
    plot(1, type = "n", xlab = "", ylab = "", xlim = 1.2 * m * c(-1, 1), ylim = 1.2 * m * c(-1, 1), asp = 1)
    circle <- seq(0, 2 * pi   0.1, 0.1)
    do.call(
        sapply, 
        list(
            vector, 
            function(x) lines(x*cos(circle), x*sin(circle),
            ...)
        )
    )
}

my_func2(dd, lty = "dashed", col = "red")

enter image description here

  •  Tags:  
  • Related