- drcパッケージのdrm()の中身を確認している
- いくつかの「作法」的関数が出てくるので、メモしておく
- match.arg(type)
my.fx <- function(x=c("a","b","c"){
x <- match.arg(x)
}
-
- のように作るとして、xを指定せずに実行すれば、最初の"a"が用いられ、そうでないときは、a,b,cのいずれかが引数で与えられていることをチェックする
- options()
options()
-
- で示される
- 以下は、実行機器に依存しないセッティング
add.smooth TRUE
check.bounds FALSE
continue "+ "
digits 7
echo TRUE
encoding "native.enc"
error NULL
expressions 5000
keep.source interactive()
keep.source.pkgs FALSE
max.print 99999
OutDec "."
prompt "> "
scipen 0
show.error.messages TRUE
timeout 60
verbose FALSE
warn 0
warning.length 1000
width 80
- option(na.action =deparse(substitute(na.action)))
- na.actionのオプション設定を関数の利用者が変更しているときに、デフォルトの設定で使わせたい、ということらしい
> deparse(substitute(na.action))
[1] "na.action"
-
- のように文字列が返り、これをoption()関数のna.actionに指定している
- substitute()はparse tree for the (unevaluated) expressionし、deparse()はTurn unevaluated expressions into character stringsする
- match.call()
- 作成している関数の中で、引数がどのように指定してあるかを呼び出す。省略指定してあってもフルネームで返す
> fun <- function(x, lower = 0, upper = 1) {
+ structure((x - lower) / (upper - lower), CALL = match.call())
+ }
> fun(4 * atan(1), u = pi)
[1] 1
attr(,"CALL")
fun(x = 4 * atan(1), upper = pi)
-
- match.call(expand.dots=FALSE)
- "..."で「その他の引数の取り扱いは全部引き継ぐ」という指定の仕方があるが、match.call(()関数で、それをやらないように設定している(?たぶん)
- attr()
> x <- 1:10
> attr(x,"dim") <- c(2, 5)
> x
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
> attr(x,"dim")
[1] 2 5
- try()
- やってはみるけどうまくいかないかもしれないようなときに使う
set.seed(123)
x <- stats::rnorm(50)
doit <- function(x)
{
x <- sample(x, replace = TRUE)
if(length(unique(x)) > 30) mean(x)
else stop("too few unique points")
}
res <- lapply(1:100, function(i) try(doit(x), TRUE))
for(i in 1:100) res[[i]] <- try(doit(x), TRUE)
unlist(res[sapply(res, function(x) !inherits(x, "try-error"))])
centre <- function(x, type) {
switch(type,
mean = mean(x),
median = median(x),
trimmed = mean(x, trim = .1))
}
x <- rcauchy(10)
centre(x, "mean")
centre(x, "median")
centre(x, "trimmed")