In R, functions can return multiple objects by using lists or named lists to encapsulate multiple data types, similar to how you’d use a class in Java. Since R doesn’t have classes in the same way, lists offer a flexible way to group various data types together.
Here’s an example of how to create an R function that returns both a list of characters and an integer:
my_function <- function() {
# Define your objects
character_list <- c("Alex", "Bot", "Charlie")
some_integer <- 42
# Return both objects in a list
return(list(names = character_list, number = some_integer))
}
# Call the function and capture the result
result <- my_function()
# Access the objects
print(result$names) # List of characters
print(result$number) # Integer
Explanation:
list(names = character_list, number = some_integer): Creates a named list with each component accessible by name.
Accessing the values: Once the function returns, use $ to access individual components, e.g., result$names or result$number.
Output:
[1] "Alex" "Bot" "Charlie"
[1] 42