Aella
Aella

Reputation: 63

Changing parametres in a function call in R

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"))

Upvotes: 0

Views: 52

Answers (2)

SamR
SamR

Reputation: 20502

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

Upvotes: 0

Waldi
Waldi

Reputation: 41260

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

Upvotes: 1

Related Questions