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

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

问题描述

仍在尝试进入 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?

我显然不能这样做:

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) list[...]<- 我十多年前在 r-help.从那时起,它被添加到 gsubfn 包中.它不需要特殊的运算符,但需要使用 list[...] 编写左侧,如下所示:

(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) attach 另一种选择是附加:

attach(myfun())
a + b

添加:withattach

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

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