2017-02-15 53 views
2

如何在输出中添加“mean =”,而不是R中的默认[1]?如何将“mean =”添加到输出中,而不是R中的默认[1]?

Test_scores <- c(50,75,80,90,99,93,65,85,95,87) #created matrix 
Hours_studied <- c(.1,.5,.6,1,3,3.5,.5,1,2,2.5) 
grade_study <- cbind(Test_scores,Hours_studied) #combined into one matrix 
return(grade_study) 

summarystat <- function(x) { #make a function to output the mean, median, sd with the output labeled (ex: mean=) 
    print(mean(x)), 
    print (median(x)) 
    print(sd(x)) 
} 

回答

4

我会做这样的事情:

summarystat <- function(x) { 
    cat(sprintf("The mean is %s\n", mean(x))) 
    cat(sprintf("The median is %s\n", median(x))) 
    cat(sprintf("The sd is %s\n", sd(x))) 

} 

summarystat(grade_study) 

输出是:

The mean is 41.685 
The median is 26.75 
The sd is 42.5506419643576 

如果你想要一个 “=” 号,那么你可以这样做:

summarystat <- function(x) { 
    cat(sprintf("mean = %s\n", mean(x))) 
    cat(sprintf("median = %s\n", median(x))) 
    cat(sprintf("sd = %s\n", sd(x))) 

} 

summarystat(grade_study) 

并且输出将是:

mean = 41.685 
median = 26.75 
sd = 42.5506419643576 
相关问题