R功能中的掩码输出

cod*_*art 1 r function mask output

我是在R中编写函数的新手,想要编写一个创建多个输出的函数,但是我想屏蔽某些对象的输出,使得它们被计算并且可以被调用,但是当它们不能直接输出时功能很有趣.例如:

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

x <- rnorm(100)
fun(x)
Run Code Online (Sandbox Code Playgroud)

在这里,我希望在运行fun(x)并且计算sd但不报告时报告平均值(当我从列表中取出sd时,我以后再也不能调用它).谢谢你的帮助!

mri*_*rip 6

有两种方法可以做到这一点.第一种是使用invisible@SenorO所示.更复杂的方法是创建一个新类并覆盖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
}
Run Code Online (Sandbox Code Playgroud)

您仍然可以像访问列表一样访问类中的值,如果您想要实际的基础列表,请调用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
Run Code Online (Sandbox Code Playgroud)