简体   繁体   English

从 function 返回两个对象

[英]Returning two objects from a function

I have two list objects that were created from two data sets.我有两个从两个数据集创建的列表对象。 I created a function that removes some random components from each list.我创建了一个 function,它从每个列表中删除了一些随机组件。 I would like the function to return these two list as an output.我希望 function 将这两个列表作为 output 返回。

For example I would like to get the new list1 and list2 objects when I run the example_func .例如,我想在运行example_func时获取新的list1list2对象。 I would like the output from the function to replace my old list objects and look something like the expected outputs.我希望 function 中的 output 替换我的旧列表对象并看起来像预期的输出。

Is this something that could be done in R?这是可以在 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)]

You can use the zeallot operator like so:您可以像这样使用zeallot运算符:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM