在 R 函数中返回多个对象 [英] Returning multiple objects in an R function
问题描述
如何在 R 函数中返回多个对象?在Java中,我会创建一个类,可能是Person
,它有一些私有变量并封装,可能是height
、age
等>
但在 R 中,我需要传递数据组.例如,如何让 R 函数同时返回字符列表和整数?
与许多其他语言不同,R 函数在严格意义上不返回多个对象.最通用的处理方法是返回一个 list
对象.因此,如果您的函数中有一个整数 foo
和一个字符串向量 bar
,您可以创建一个组合这些项目的列表:
foo <- 12bar <- c("a", "b", "e")newList <- list("integer" = foo, "names" = bar)
然后返回
这个列表.
调用您的函数后,您可以使用newList$integer
或newList$names
访问其中的每一个.
其他对象类型可能适用于各种目的,但 list
对象是一个很好的入门方法.
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 an list of characters and an integer?
Unlike many other languages, R functions don't return multiple objects in the strict sense. The most general way to handle this is to return a list
object. So if you have an integer foo
and a vector of strings bar
in your function, you could create a list that combines these items:
foo <- 12
bar <- c("a", "b", "e")
newList <- list("integer" = foo, "names" = bar)
Then return
this list.
After calling your function, you can then access each of these with newList$integer
or newList$names
.
Other object types might work better for various purposes, but the list
object is a good way to get started.
这篇关于在 R 函数中返回多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!