【问题标题】:Store results of function in complex object (?) in R将函数结果存储在 R 中的复杂对象 (?) 中
【发布时间】:2019-05-11 05:51:50
【问题描述】:

每个人都知道这个功能:

    fitted_lm = lm(mpg ~ wt, mtcars)
    > class(fitted_lm)
    [1] "lm"

    fitted_lm$

在我的全局环境中,我看到 fit_lm 存储为一个列表,但是当我在对象上调用类函数时,我得到“lm”作为结果。这些对象允许它使用“$”符号轻松访问不同的值。我怎样才能以这种方式存储自己的结果?

例如这样的:

complex_output <- function(x) {
    row.means <- rowMeans(x)
    col.means <- colMeans(x)
    result <- list(row.means, col.means)
    return(result)
}

complex_result <- complex_output(x = mtcars)
complex_result[[1]]
complex_result$ # does not work

我当然可以通过双括号访问所有结果,但是使用“$”符号访问它们会更方便。我该怎么做?

【问题讨论】:

    标签: r function object


    【解决方案1】:

    尝试为您的函数生成的列表中的元素指定名称:

    complex_output <- function(x) {
        row.means <- rowMeans(x)
        col.means <- colMeans(x)
        result <- list(r=row.means, c=col.means)
        return(result)
    }
    
    complex_result$r
    

    【讨论】:

    • 哇,非常感谢您的快速和出色的响应。真是太棒了:-)
    • 当然!但我必须等八分钟才能做到这一点:-)
    猜你喜欢
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多