Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (5.3k points)
edited by

How can I return multiple objects in an R function? In Java, I would make a Class, maybe Person which has some private variables and encapsulates, maybe, height, age, etc.

But in R, I need to pass around groups of data. For example, how can I make an R function return both a list of characters and an integer?

2 Answers

0 votes
by
edited by

In R programming, functions do not return multiple values, however, you can create a list that contains multiple objects that you want a function to return.

For example:

x <- c(3,4,7,9,34,24,5,7,8)

fun = function(x){

  mn = mean(x)

  lt = list(f1=table(x),std=sd(x))

  newlist <- list(lt,mn)

  return(newlist)

}

fun(x)

Output:

[[1]]

[[1]]$f1

x

 3  4  5  7  8  9 24 34 

 1  1  1  2  1  1  1  1 

[[1]]$std

[1] 10.55673

[[2]]

[1] 11.22222

If you wish to learn R Programming visit this R Programming Course by Intellipaat.

0 votes
ago by (1.9k points)

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

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...