以下函数给出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
由于用户@ dominic-comtois强调here,因此packs
变量中可以包含更多软件包。所以,
通常包含内部is.X(is.vector
,is.numeric
等)和所有isX(isS4
,isOpen
等)功能的软件包是什么? ?