首页 > 解决方案 > 通常包含内部 is.X(is.vector、is.numeric 等)和所有 isX(isS4、isOpen 等)函数的包是什么?

问题描述

下面的函数给出了 R 中对象的所有结构。这个函数(加上dput()/str()表示对象属性)完全限定了任意 R 对象的所有内容。

ObjectStructure <- function(x, ShowAll=FALSE) { 
    op <- options("warn")
    options(warn=-1)  # Assign "-1" to warn option to temporarily close warnings
    on.exit(options(op)) # Reset the settings to initial ones after exit from the ObjectStructure function
    is.Functions <- grep(methods(is), pattern="<-", invert=TRUE, value=TRUE) # 55 (is.X) functions
    isDotlessFunctions <- character()
    packs <- c('base', 'utils', 'methods') # include more packages if needed
    for (pkg in packs) {
        library(pkg, character.only = TRUE)
        objects <- grep("^is.+\\w$", ls(envir=as.environment(paste('package', pkg, sep=':'))), value=TRUE)
        objects <- grep("<-", objects, invert=TRUE, value=TRUE)
        if (length(objects) > 0) 
          isDotlessFunctions <- append(isDotlessFunctions, objects[sapply(objects, function(x) class(eval(parse(text=x))) == "function")])
      }

    FunctionsList <- union(is.Functions, isDotlessFunctions)
    result <- data.frame(test=character(), value=character(), warn=character(), stringsAsFactors=FALSE)

    # Loop all the "is.(...)" functions and save the results
    for(islev in FunctionsList) {
    res <- try(eval(call(islev,x)),silent=TRUE) # In cases of error, let error be processed
    # in errored cases, try produces try-error object that contains error message
    if(class(res)=="try-error") { next() # In case of error, ignore current iteration and pass to the next iteration in the loop
    } else if (length(res)>1) {
          warn <- "*Applies only to the first element of the provided object"
          value <- paste(res,"*",sep="")
        } else {
          warn <- ""
          value <- res
        }
        result[nrow(result)+1,] <- list(islev, value, warn)
      }  
      result <- result[order(result$value, decreasing=TRUE),] # Order the results
      rownames(result) <- NULL # to arrange row numbers in a way that they start from 1 and ordered
      if(ShowAll) return(result) # Show only the structures that give TRUE
      else return(result[which(result$value=="TRUE"),]) # All the function results that give a TRUE/FALSE value
    }

ObjectStructure(1L, TRUE) # See how the function works 

正如用户@domonic-comtois在这里packs强调的那样,变量中可以包含更多的包。所以,

通常包含内部 is.X ( , 等) 和所有 isX ( 等) 函数的is.vectoris.numericisS4什么isOpen

标签: rfunctionobjectstructure

解决方案


推荐阅读