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

R中是否有内置函数来检查变量类型是否被保留?,r,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.fact

假设您有一个输入
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如果您只想比较两个对象,您可能希望使用
all.equal()
idential()
而不是尝试生成所有可能的类成对组合(因为该数字可能是无限的)

如果试图进行类型强制,则应用
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
#活动绑定

保留您的函数看起来需要的不仅仅是保留
类型
a
b
都属于
integer
@MikeH类。您是RistHT,但在很多情况下,我不认为一个空整数是整数。类似于C中通过
inta
定义的变量,但是仍然有值
integer
NA
ìnteger(0)
。此外,它不会区分
1.345
1.345/0
,因为它们都是
数字的
。当然。正如Mike H.上面提到的,您要求比较对象的多个特征(
模式()
,但也要求比较
长度()
)。没有内置的函数可以这样做,因此您必须准确地确定规则是什么,然后编写相应的函数。也许可以更新您的问题,以指定除了类或模式之外,您还希望不可比较的其他内容。还请注意,
NA
以R分类(请参见
NA_real\u
NA_字符
,等等).好的,我想你让我意识到这是我的代码的问题,而不是R的问题;-)我必须用新的知识重新检查我的代码,然后决定如何继续-但再次感谢:我没有意识到这个选项。
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)
  }
}
# 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