I just like the subroutine to spit out results (Mean, Std.dev, etc.) and also be able to access the results for further processing, i.e.,

v$Mean

v$Std.dev

On 3/26/2024 11:24 AM, Richard O'Keefe wrote:
Not clear what you mean by "saved".
If you call a function and the result is printed, the result is
remembered for a wee while in
the variable .Last.value, so you can do
function.with.interesting.result(.......)
retained.interesting.result <- .Last.value
or even
.Last.value -> retained.interesting.result
If you know before you start writing the expression that you want to
save the value,
you can wrap the assignment in parentheses, making it an expression:

(retained.interesting.result <- function.with.interesting.result(......))

On Tue, 26 Mar 2024 at 15:03, Steven Yen <st...@ntu.edu.tw> wrote:
How can I have both printout and saved results at the same time.

The subroutine first return "out" and the printout gets printed, but not
saved.

I then run the "invisible" line. Results got saved and accessible but no
printout.

How can I have both printout and also have the results saved? Thank you!

  > dstat4 <- function(data,digits=3){
+   Mean    <- apply(data,2,mean,na.rm=TRUE)
+   Std.dev <- apply(data,2,sd,  na.rm=TRUE)
+   Min <- apply(data,2,min,na.rm=TRUE)
+   Max <- apply(data,2,max,na.rm=TRUE)
+   Obs <- dim(data)[1]
+   out <-round(cbind(Mean,Std.dev,Min,Max,Obs),digits)
+   out
+ # invisible(list(Mean=Mean,Std.dev=Std.dev,Min=Min,Max=Max))
+ }
  > x1<-rnorm(n=5,mean=5, sd=1)
  > x2<-rnorm(n=5,mean=10,sd=2)
  > w<-rnorm(n=5,mean=2,sd=0.3)
  > mydata<-data.frame(cbind(x1,x2))
  > v<-dstat4(mydata); v
       Mean Std.dev   Min    Max Obs
x1  5.000   0.922 3.900  6.282   5
x2 10.769   1.713 9.209 13.346   5
  > v$Mean
Error in v$Mean : $ operator is invalid for atomic vectors
  > dstat4 <- function(data,digits=3){
+   Mean    <- apply(data,2,mean,na.rm=TRUE)
+   Std.dev <- apply(data,2,sd,  na.rm=TRUE)
+   Min <- apply(data,2,min,na.rm=TRUE)
+   Max <- apply(data,2,max,na.rm=TRUE)
+   Obs <- dim(data)[1]
+   out <-round(cbind(Mean,Std.dev,Min,Max,Obs),digits)
+ # out
+   invisible(list(Mean=Mean,Std.dev=Std.dev,Min=Min,Max=Max))
+ }

  > v<-dstat4(mydata)
  > v$Mean
        x1       x2
4.233051 9.564454

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to