如何从一个返回多个值的函数中赋值? [英] How to assign from a function which returns more than one value?

查看:125
本文介绍了如何从一个返回多个值的函数中赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仍试图进入R逻辑...(在LHS上)解压缩函数返回多个值的结果的最佳"方法是什么?

Still trying to get into the R logic... what is the "best" way to unpack (on LHS) the results from a function returning multiple values?

我显然无法做到这一点:

I can't do this apparently:

R> functionReturningTwoValues <- function() { return(c(1, 2)) }
R> functionReturningTwoValues()
[1] 1 2
R> a, b <- functionReturningTwoValues()
Error: unexpected ',' in "a,"
R> c(a, b) <- functionReturningTwoValues()
Error in c(a, b) <- functionReturningTwoValues() : object 'a' not found

我真的必须执行以下操作吗?

must I really do the following?

R> r <- functionReturningTwoValues()
R> a <- r[1]; b <- r[2]

或者R程序员会写这样的东西吗?

or would the R programmer write something more like this:

R> functionReturningTwoValues <- function() {return(list(first=1, second=2))}
R> r <- functionReturningTwoValues()
R> r$first
[1] 1
R> r$second
[1] 2

-编辑以回答Shane的问题---

--- edited to answer Shane's questions ---

我真的不需要给结果值部分起名字.我将一个聚合函数应用于第一个组件,将另一个聚合函数应用于第二个组件(minmax.如果两个组件的功能相同,则无需拆分它们).

I don't really need giving names to the result value parts. I am applying one aggregate function to the first component and an other to the second component (min and max. if it was the same function for both components I would not need splitting them).

推荐答案

(1)列表[...]<-我十多年前在

(1) list[...]<- I had posted this over a decade ago on r-help. Since then it has been added to the gsubfn package. It does not require a special operator but does require that the left hand side be written using list[...] like this:

library(gsubfn)  # need 0.7-0 or later
list[a, b] <- functionReturningTwoValues()

如果您只需要第一个或第二个组件,那么所有这些也都可以工作:

If you only need the first or second component these all work too:

list[a] <- functionReturningTwoValues()
list[a, ] <- functionReturningTwoValues()
list[, b] <- functionReturningTwoValues()

(当然,如果只需要一个值,那么functionReturningTwoValues()[[1]]functionReturningTwoValues()[[2]]就足够了.)

(Of course, if you only needed one value then functionReturningTwoValues()[[1]] or functionReturningTwoValues()[[2]] would be sufficient.)

有关更多示例,请参见引用的r-help线程.

See the cited r-help thread for more examples.

(2)with 如果意图是随后仅合并多个值,并命名返回值,则一个简单的替代方法是使用with:

(2) with If the intent is merely to combine the multiple values subsequently and the return values are named then a simple alternative is to use with :

myfun <- function() list(a = 1, b = 2)

list[a, b] <- myfun()
a + b

# same
with(myfun(), a + b)

(3)附加:另一种替代方法是:

(3) attach Another alternative is attach:

attach(myfun())
a + b

已添加:withattach

这篇关于如何从一个返回多个值的函数中赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆