三生石@ 2009-12-01 14:27 采纳率: 100%
浏览 646
已采纳

如何从一个返回多个值的函数赋值?

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]

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

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

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).

转载于:https://stackoverflow.com/questions/1826519/how-to-assign-from-a-function-which-returns-more-than-one-value

  • 写回答

12条回答 默认 最新

  • 三生石@ 2013-02-28 16:23
    关注

    (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()
    

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

    See the cited r-help thread for more examples.

    (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 Another alternative is attach:

    attach(myfun())
    a + b
    

    ADDED: with and attach

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(11条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集