R语言是否有内置函数检查变量类型保留?求实现preserved函数方案
Checking if Variable Type is Preserved in R: Implementing the
preserved() Function Great question! Looking at your examples, it's clear that your definition of "type preserved" goes beyond just basic type equality—you want to ensure the output is a valid, non-empty, non-NULL, non-all-missing value that matches the original variable's type exactly. Let's build this function step by step.
The preserved() Function Implementation
Here's a function that aligns perfectly with your expected outputs:
preserved <- function(original, transformed) { # First, rule out NULL cases immediately if (is.null(original) || is.null(transformed)) { return(FALSE) } # Check that both objects have identical underlying type and class # (this handles edge cases like factors, which have typeof = integer but class = factor) type_matches <- typeof(original) == typeof(transformed) && identical(class(original), class(transformed)) # Ensure neither object is empty (length 0) non_empty <- length(original) > 0 && length(transformed) > 0 # Make sure the transformed value isn't entirely missing not_all_missing <- !all(is.na(transformed)) # Return TRUE only if all conditions are met all(type_matches, non_empty, not_all_missing) }
Testing with Your Example Cases
Let's verify this works with the variables you defined:
# Set up test variables a <- 1L # Integer, length 1, non-missing b <- a[FALSE] # Empty integer vector (length 0) c <- a[2] # Integer vector with NA (length 1, all missing) d <- ncol(a) # NULL e <- a/0 # Inf (double type, not integer) f <- 1 # Numeric (double, not integer) g <- as.factor(a)# Factor class, not integer # Run tests 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, g) # FALSE ✔️
Key Details Explained
- NULL Check: NULL is a special case in R that doesn't fit standard type categories, so we immediately return FALSE if either input is NULL.
- Type + Class Matching: Using both
typeof()(for underlying storage type) andclass()(for object-oriented class) ensures we catch cases like factors, which share an underlying integer type but are distinct classes. - Non-Empty Check: This rules out empty vectors like
integer(0), which matches your example wherepreserved(a, b)returns FALSE. - Non-All-Missing Check: This handles cases where the output is the right type but entirely missing (like
NA_integer_), which is whypreserved(a, c)returns FALSE in your example.
If you need to tweak the definition of "preserved" (e.g., allow empty vectors or ignore missing values), you can simply remove or adjust the corresponding condition in the function.
内容的提问来源于stack exchange,提问作者Christoph
相关产品推荐
相关产品推荐

