1

私は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 を取り出すと、後でそれを呼び出すことができなくなります)。助けてくれてありがとう!

4

2 に答える 2

6

There are two ways to do this. The first is to use invisible as shown by @SenorO. The more complicated way is to create a new class and override the print method. If you create a new class, then every time the object gets printed, only the mean will show up:

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
}

You can still access the values in the class as if it were a list, and if you want the actual underlying list, call 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
于 2013-10-10T20:00:43.967 に答える
3

printと_invisible

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
于 2013-10-10T19:53:47.303 に答える