我寫了一個繪制圓圈的函式。默認情況下,線條型別為“實心”,顏色為黑色。但是,我希望它們可以在函式呼叫中進行更改。是否可以?
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"))
uj5u.com熱心網友回復:
您可以將額外的引數傳遞給函式:
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')

uj5u.com熱心網友回復:
Waldi 建議的方式適用于這兩個引數。但是,您必須手動添加要傳遞的每個引數。
或者,使用do.call將 傳遞...給所需的函式 - 這意味著您將能夠傳遞任何接受的引數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")

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/412372.html
標籤:
