在R函数中返回多个对象 [英] Returning multiple objects in an R function
问题描述
如何在R函数中返回多个对象?在Java中,我会创建一个类,也许 Person
,它有一些私有变量和封装,也许 height
, age
等。
但是在R中,我需要传递几组数据。例如,如何让R函数返回一个字符列表和一个整数?
与其他许多语言不同, R函数在严格意义上不返回多个对象。处理这个问题最常用的方法是返回一个 list
对象。所以如果你的函数中有一个整数 foo
和一个字符串向量 bar
,你可以创建一个列表这些项目:
foo < - 12
bar <-c(a,b, e)
newList< - list(integer= foo,names= bar)
然后返回
此列表。
调用你的函数后,你可以用 newList $ integer
或 newList $名称
。
其他对象类型可能更适合各种用途,但 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屋!