简体   繁体   English

格式化R输出

[英]Formatting R output

The summary function in R gives an output as follows R中的summary函数给出如下输出

         Variable 1
 Min.   :-2.192e+09                         
 1st Qu.:0.000e+00                         
 Median :2.632e+05                         
 Mean   :7.933e+06                        
 3rd Qu.:4.668e+06                        
 Max.   :1.124e+09                         
 NA's   :277   

I want to get an output in the following format: 我想获得以下格式的输出:

            Min  1st Qu  Median  Mean  3rd Qu  Max  NA's
Variable 1   -     -      -       -      -      -    -

Variable 2   -     -      -       -      -      -    -

How can I do that and export to Excel? 我该怎么做并导出到Excel?

If I'm right, you want to write summary information of vectors to Excel? 如果我是对的,您想将向量的摘要信息写入Excel吗? If so, this might work for you (package readr required, or you may use write.csv() ): 如果是这样,这可能对您有用(需要使用包读取器,或者您可以使用write.csv() ):

tmp <- data.frame(
  var1 = runif(100, min = 5, max = 50),
  var2 = c(runif(99, min = 50, max = 150), NA),
  var3 = runif(100, min = 150, max = 250)
)

tmp <- as.data.frame(t(do.call(cbind, lapply(tmp, function(x) {
  # save summary information
  v <- as.vector(summary(x))
  # if vector has no NAs, manually add 0, to ensure equal 
  # length of vectors for column bind
  if (length(v) < 7) v <- c(v, 0)
  # return summary
  v
}))))

colnames(tmp) <- c("Min.", "1st Qu.", "Median", "Mean", "3rd Qu.", "Max.", "NA's")

# result so far:
##         Min. 1st Qu. Median   Mean 3rd Qu.   Max. NA's
## var1   5.097   15.12  26.83  26.46   36.89  49.75    0
## var2  50.900   83.08 104.50 103.80  129.00 149.20    1
## var3 151.200  166.80 200.30 197.00  223.70 248.50    0

readr::write_excel_csv(tmp, "summary.csv")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM