Home > OS >  Returning two objects from a function
Returning two objects from a function

Time:06-01

I have two list objects that were created from two data sets. I created a function that removes some random components from each list. I would like the function to return these two list as an output.

For example I would like to get the new list1 and list2 objects when I run the example_func. I would like the output from the function to replace my old list objects and look something like the expected outputs.

Is this something that could be done in R?


value <- rep(c(1:5), 10)
id <- rep(c("A", "B"), 25)
df <- data.frame(ID = as.factor(id),
                 value = value)

list1 <- df %>% 
  group_by(ID) %>% 
  group_split()

value <- rep(c(8:12), 10)
id <- rep(c("A", "B"), 25)
df <- data.frame(ID = as.factor(id),
                 value = value)

list2 <- df %>% 
  group_by(ID) %>% 
  group_split()

example_func <- function(l1, l2){
  l1 <- l1[-c(1)]
  l2 <- l2[c(1)]
}

# Expected outcome
expected_list1 <- list1[-c(1)]
expected_list2 <- list2[-c(1)]

CodePudding user response:

You can use the zeallot operator like so:

library(zeallot)

example_func <- function(l1, l2){
  l1 <- l1[-c(1)]
  l2 <- l2[c(1)]
  list(l1, l2)
}

c(expected_list1, expected_list2) %<-% example_func(list1, list2)
  • Related