Investigating Objects and Functions in R
str() Function
The str() function provides a compact, human-readable description of an R object’s structure. It’s particularly useful for getting a quick overview of complex objects.
# Create a complex object my_list <- list(name = "Alice", age = 30, scores = c(90, 85, 88)) # Use str() to understand its structure str(my_list) # Output Example: # List of 3 # $ name : chr "Alice" # $ age : num 30 # $ scores: num [1:3] 90 85 88
summary() Function
The summary() function provides a statistical summary for various objects, such as vectors, data frames, and models.
# Create a numeric vector num_vector <- c(1, 2, 3, 4, 5) # Use summary() to get a statistical summary summary(num_vector) # Output Example: # Min. 1st Qu. Median Mean 3rd Qu. Max. # 1.00 2.00 3.00 3.00 4.00 5.00
attributes() Function
The attributes() function returns the attributes of an R object, such as names, dimensions, or class.
# Create a matrix my_matrix <- matrix(1:6, nrow = 2) # Use attributes() to get its attributes attributes(my_matrix) # Output Example: # $dim # [1] 2 3
typeof() and class() Functions
These functions provide information about the type and class of an object.
# Create different types of objects num <- 42 char <- "Hello" df <- data.frame(x = 1:3, y = letters[1:3]) # Use typeof() and class() to get type and class information typeof(num) # Returns "double" class(char) # Returns "character" class(df) # Returns "data.frame"
Exploring Functions
To understand the details of a function, including its code and documentation:
?function_name: Accesses the help documentation for the function.
?mean
args(function_name): Lists the arguments of the function.
args(mean)
body(function_name): Displays the body of the function if it’s user-defined.
my_function <- function(x) { return(x^2) } body(my_function)
traceback() Function
The traceback() function is useful for debugging by showing the call stack after an error occurs.
# Generate an error tryCatch({ log("a") }, error = function(e) { traceback() }) # Output Example: # 3: stop("non-numeric argument to mathematical function") at #<anonymous> # 2: log("a") at #<anonymous> # 1: tryCatch({ # log("a") # }, error = function(e) { # traceback() # })
Summary
To understand or investigate an object or a piece of code in R, you can use functions like str(), summary(), attributes(), typeof(), class(), and body(). Additionally, functions like ?function_name for documentation and traceback() for debugging provide further insights. These tools help in exploring and comprehending the nature and details of R objects and functions, making it easier to work with complex code and data structures.