bug^君 2009-12-01 14:27 采纳率: 25%
浏览 404
已采纳

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

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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?