我正在尝试在下面的函数(does not contain
)中为单词foo
找到合适的R代码?
换句话说,如何确保传递给...
的对象中包含至少一个类"POSIXt"
的实例?
A <- Sys.time()
B <- as.POSIXlt(A)
foo <- function(...){
if(class(list(...)) does not contain "POSIXt") stop("Error") ## Send a Message
}
foo(A, B)
答案 0 :(得分:2)
假设POSIXlt
类是%in%
传递的任何参数,我们遍历list
('l1')获取class
并检查{{1} } POSIXt
%in%
class
或使用foo <- function(...){
l1 <- list(...)
if("POSIXt" %in% unlist(sapply(l1, class))) "Good Class" else "Bad Class"
}
foo(A, B)
#[1] "Good Class"
foo(LETTERS[1:4], 1:5, letters[1:3])
#[1] "Bad Class"
inherits
如果我们需要停止,如果没有foo <- function(...){
l1 <- list(...)
if(any(sapply(l1, inherits, "POSIXct"))) "Good Class" else "Bad Class"
}
foo(LETTERS[1:4], 1:5, letters[1:3])
#[1] "Bad Class"
POSIXct
错误:任何(sapply(l1,inherits,“POSIXct”))不是TRUE
foo <- function(...){
l1 <- list(...)
stopifnot(any(sapply(l1, inherits, "POSIXct")))
}
foo(LETTERS[1:4], 1:5, letters[1:3])
或者,如果我们需要自定义错误消息,请在评论中使用foo(A, 1:5) #no error
作为@rnorouzian metnioned
stop
foo错误(LETTERS [1:4],1:5,字母[1:3]):错误