R中是否有内置函数来检查变量类型是否被保留?

时间:2018-04-24 12:38:41

标签: r

假设您有一个输入a,它将进入现有函数fun。我正在寻找一个函数preserved(a, fun(a)),如果类型未更改则返回TRUE,否则返回FALSE

示例:

a <- 1L # [1] 1 - integer
b <- a[FALSE] # integer(0)
c <- a[2] # [1] NA
d <- ncol(a) # NULL
e <- a/0 # [1] Inf
f <- 1 # [1] 1 - numeric
g <- as.factor(a) # [1] 1 Levels: 1

预期产出:

preserved(a, 2L) = TRUE
preserved(a, b) = FALSE
preserved(a, c) = FALSE
preserved(a, d) = FALSE
preserved(a, e) = FALSE
preserved(a, f) = FALSE
preserved(a, f) = FALSE
preserved(a, g) = FALSE

糟糕的黑客(没有矢量化)将是

preserved <- function(a, b) {
  if (length(b) == length(a)) {
    if (is.na(b) == is.na(a) & 
        class(b) == class(a) &
        is.null(b) == is.null(a) &
        is.nan(b) == is.nan(a) &
        is.factor(b) == is.factor(a)) {
      return(TRUE)
    } else {
      return(FALSE)
    }
  } else {
    return(FALSE)
  }
}

1 个答案:

答案 0 :(得分:2)

如果您只想比较两个对象,您可能希望使用all.equal()identical()而不是尝试生成每个可能的成对类组合(因为该数字可能是无限的)。

如果尝试输入类型强制,则应用makeActiveBinding()来发布消息(或警告或错误),这可能会更有用:

# active binding
preserved <- local( {
    x <- NULL
    function(v) {
        if (!missing(v)) {
            if (class(x) != class(v)) {
                message(sprintf("Object is being coerced from %s to %s", class(x), class(v)))
            }
            x <<- v
        }
        x
    }
})
makeActiveBinding("z", preserved, .GlobalEnv)
z
## NULL
z <- 2
## Object is being coerced from NULL to numeric
z <- "hello"
## Object is being coerced from numeric to character
z <- factor("a", levels = c("a", "b", "c"))
## Object is being coerced from character to factor
z
## [1] a
## Levels: a b c