Forcing specific data types as arguments to a function

前端 未结 3 1269
傲寒
傲寒 2020-12-31 13:01

I was just wondering if there was a way to force a function to only accept certain data types, without having to check for it within the function; or, is this not possible b

3条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-31 13:20

    I've found stopifnot() to be highly useful for these situations as well.

    x <- function(n) { 
    stopifnot(is.vector(n) && length(n)==1)
    print(n)
    }
    

    The reason it is so useful is because it provides a pretty clear error message to the user if the condition is false.

提交回复
热议问题