[R] Printout and saved results

Steven Yen @tyen @end|ng |rom ntu@edu@tw
Tue Mar 26 03:02:55 CET 2024


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



More information about the R-help mailing list