【问题标题】:Mask output in R functionR函数中的掩码输出
【发布时间】:2013-10-18 17:58:22
【问题描述】:

我是在 R 中编写函数的新手,想编写一个创建多个输出的函数,但我想屏蔽某些对象的输出,以便计算并调用它们,但不能直接调用功能好玩时输出。例如:

fun <- function(x){
    mean <- mean(x)
    sd <- sd(x)
    return(list(sd = sd, mean = mean))
}

x <- rnorm(100)
fun(x)

在这里,我希望在运行 fun(x) 时报告均值,并计算 sd 但不报告(当我将 sd 从列表中取出时,我以后无法再调用它)。感谢您的帮助!

【问题讨论】:

  • 所以您希望fun(x) 的打印输出包含均值而不包含标准差?

标签: r function output mask


【解决方案1】:

有两种方法可以做到这一点。第一种是使用@SenorO 所示的invisible。更复杂的方法是创建一个新类并覆盖 print 方法。如果你创建一个新类,那么每次打印对象时,只会显示平均值:

print.myclass<-function(x){
    cat("Mean is:",x$mean ,"\n")
}

fun <- function(x){
    mean <- mean(x)
    sd <- sd(x)
    ret<-list(sd = sd, mean = mean)
    class(ret)<-"myclass"
    ret
}

您仍然可以像访问列表一样访问类中的值,如果您想要实际的底层列表,请调用 unclass:

> x<-fun(rnorm(100))
> x
Mean is: -0.03470428 
> x$mean
[1] -0.03470428
> x$sd
[1] 0.9950132
> unclass(x)
$sd
[1] 0.9950132

$mean
[1] -0.03470428

【讨论】:

  • 呸,打我! :)
  • 一般情况下,我会使用class(ret) &lt;- c("myclass", class(ret)) 来方便继承任何未涵盖的现有方法。
【解决方案2】:

使用printinvisible

fun <- function(x){
    print(mean <- mean(x))
    sd <- sd(x)
    return(invisible(list(sd = sd, mean = mean)))
}

导致:

> y = fun(x)
[1] -0.01194926
> y$sd
[1] 0.9474502

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-24
    • 2018-12-14
    • 1970-01-01
    • 2013-11-30
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    相关资源
    最近更新 更多