【问题标题】:How to format the output of a function when it is a list当函数是列表时如何格式化函数的输出
【发布时间】:2023-03-13 18:29:02
【问题描述】:

我有一个函数f,它返回一个具有不同输出的列表L。假设输出由下式给出:

L[[1]] A vector of values
L[[2]] A matrix 
L[[3]] The result of a glm (or any regression model)

为了方便用户获取信息,我想给出名字

(vector = L[[1]], matrix = L[[2]], fit = L[[3]])

以便用户可以写L$vectorL$matrixL$fit

我该怎么做?我认为这个想法类似于glm 中使用的想法,因为它的输出是一个列表,但您可以通过$coefficients 获得系数。

谢谢你,

【问题讨论】:

  • 列表(向量 = L[[1]],矩阵 = L[[2]],拟合 = L[[3]])

标签: r list function format output


【解决方案1】:

您可以为列表元素指定名称:

> L = list(values = "A vector of values",
+          matrix = matrix(1,3,3),
+          result = 1)
> L
$values
[1] "A vector of values"

$matrix
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    1

$result
[1] 1

那么你可以通过几种方式引用列表元素,例如

> L[[3]]
[1] 1
> L$result
[1] 1
> L[['result']]
[1] 1

【讨论】:

  • 谢谢,没想到这么简单。如果我写 names(L) 我会得到不同的选项(vectormatrixfit)但是当你写 L$ 并按下 TAB 按钮时,我没有名字。有什么想法吗?
  • 在RStudio中,如果你定义了L然后你写L$,你会看到列表元素的名字作为一个弹出列表。
  • 在某些界面未按预期运行的情况下,我不得不重新启动 RStudio。这有帮助吗?
【解决方案2】:

你可以试试:

result=list(vector=c(1,2,....), matrix=matrix, fit=model)
return(result)

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多