gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:01:55 26 4
gpt4 key购买 nike

假设您有一个输入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

糟糕的 hack(未矢量化)将是

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)
}
}

最佳答案

如果您只想比较两个对象,您可能希望使用 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

关于r - R中是否有内置函数来检查变量类型是否被保留?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50001927/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com