我正在嘗試撰寫一個函式,該函式接受任意數量的物件并在串列中回傳它們。它應該為不存在的物件顯示警告,但回傳那些確實存在的物件的串列。
這是一個例子。
a <- data.frame(A = 1:2)
b <- 4
c <- list(5,4,3)
f <- function(...) {
list(...)
}
# Function returns a list(a,b,c)
f(a,b,c)
# Function errors as d does not exist
# Error in test(a, b, c, d): object 'd' not found
f(a, b, c, d)
我想修改f,從而使該函式回傳list(a,b,c)的f(a, b, c, d)加警告的說法d不存在。
我不知道 R 何時嘗試查找,d但我正在考慮檢查哪些物件存在并將串列子集為那些物件。
list_in <- list(...)
list_in[[(sapply(..., exists))]]
但錯誤似乎發生在 R 甚至開始嘗試運行函式代碼之前?
uj5u.com熱心網友回復:
我建議不要使用這樣的函式。擁有一個在呼叫不存在的變數時不會拋出錯誤的函式并不是一個好習慣。它不是慣用的 R,并且很容易通過簡單的拼寫錯誤導致重大問題。
這個版本在直接傳遞數字、字符或運算式時也不起作用,例如f(1 1, "hello", a),盡管可以通過一些作業來做到這一點。
f <- function(...) {
all_vars <- as.list(match.call())[-1]
all_names <- sapply(all_vars, is.name)
if(any(!all_names)) stop("Only named objects can be passed to function f")
var_names <- sapply(all_vars, as.character)
var_exists <- sapply(var_names, exists)
if(any(!var_exists))
{
warning("Variables ", paste(var_names[!var_exists], collapse = ", "),
" were not found in the search path.")
}
lapply(var_names[var_exists], get, env = parent.frame())
}
所以,例如。
a <- data.frame(A = 1:2)
b <- 4
c <- list(5,4,3)
f(a, b, c, d, e)
#> [[1]]
#> A
#> 1 1
#> 2 2
#>
#> [[2]]
#> [1] 4
#>
#> [[3]]
#> [[3]][[1]]
#> [1] 5
#>
#> [[3]][[2]]
#> [1] 4
#>
#> [[3]][[3]]
#> [1] 3
#> Warning message:
#> In f(a, b, c, d, e) : Variables d, e were not found in the search path.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/349345.html
