logo
down
shadow

Restructure output of R summary function


Restructure output of R summary function

By : user2956056
Date : November 22 2020, 10:54 AM
I wish did fix the issue. Is there an easy way to change the output format for R's summary function so that the results print in a column instead of row? R does this automatically when you pass summary a data frame. I'd like to print summary statistics in a column when I pass it a single vector. So instead of this: , Sure. Treat it as a data.frame:
code :
set.seed(1)
x <- sample(30, 100, TRUE)

summary(x)
#    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#    1.00   10.00   15.00   16.03   23.25   30.00 
summary(data.frame(x))
#        x        
#  Min.   : 1.00  
#  1st Qu.:10.00  
#  Median :15.00  
#  Mean   :16.03  
#  3rd Qu.:23.25  
#  Max.   :30.00
data.frame(val = unclass(summary(x)))
#           val
# Min.     1.00
# 1st Qu. 10.00
# Median  15.00
# Mean    16.03
# 3rd Qu. 23.25
# Max.    30.00
stack(summary(x))
#   values     ind
# 1   1.00    Min.
# 2  10.00 1st Qu.
# 3  15.00  Median
# 4  16.03    Mean
# 5  23.25 3rd Qu.
# 6  30.00    Max.


Share : facebook icon twitter icon
calling summary() from within a function does not output anything

calling summary() from within a function does not output anything


By : Daniel Murillo Backp
Date : March 29 2020, 07:55 AM
should help you out You're calling the function summary but not printing the result. Just change it to:
code :
 print(summary(mydata))
The output of the summary function

The output of the summary function


By : gerer
Date : March 29 2020, 07:55 AM
wish helps you I would like to get equal length output using: , Adapt the summary function (enter summary.default to see it):
code :
mysummary <- function (object, ..., digits = max(3L, getOption("digits") - 
                                                   3L)) 
{
  if (is.factor(object)) 
    return(summary.factor(object, ...))
  else if (is.matrix(object)) 
    return(summary.matrix(object, digits = digits, ...))
  value <- if (is.logical(object)) 
    c(Mode = "logical", {
      tb <- table(object, exclude = NULL)
      if (!is.null(n <- dimnames(tb)[[1L]]) && any(iN <- is.na(n))) dimnames(tb)[[1L]][iN] <- "NA's"
      tb
    })
  else if (is.numeric(object)) {
    nas <- is.na(object)
    object <- object[!nas]
    qq <- stats::quantile(object)
    qq <- signif(c(qq[1L:3L], mean(object), qq[4L:5L]), digits)
    names(qq) <- c("Min.", "1st Qu.", "Median", "Mean", "3rd Qu.", 
                   "Max.")
   # if (any(nas)) 
      c(qq, `NA's` = sum(nas))
   # else qq
  }
  else if (is.recursive(object) && !is.language(object) && 
             (n <- length(object))) {
    sumry <- array("", c(n, 3L), list(names(object), c("Length", 
                                                       "Class", "Mode")))
    ll <- numeric(n)
    for (i in 1L:n) {
      ii <- object[[i]]
      ll[i] <- length(ii)
      cls <- oldClass(ii)
      sumry[i, 2L] <- if (length(cls)) 
        cls[1L]
      else "-none-"
      sumry[i, 3L] <- mode(ii)
    }
    sumry[, 1L] <- format(as.integer(ll))
    sumry
  }
  else c(Length = length(object), Class = class(object), Mode = mode(object))
  class(value) <- c("summaryDefault", "table")
  value
}
lapply(df, mysummary)
sapply(df, mysummary)
Extending R's summary function (or creating a new function with similar output) to display factors as percent of total

Extending R's summary function (or creating a new function with similar output) to display factors as percent of total


By : Florin Toader
Date : March 29 2020, 07:55 AM
hop of those help? We can borrow from the existing summary routines and do this a bit less invasively by giving the factors a transient extra class attribute.
code :
summary.my.factor<-function(object,...) {
  x<-prop.table(table(object))
  setNames(sprintf("%1.2f%%",100*x),names(x))
}

my.summary<-function(object,...) {
  f<-function(x) if(inherits(x,"factor")) structure(x,class=c("my.factor",class(x))) else x
  summary(as.data.frame(lapply(object,f)),...)
}

my.summary(chickwts)
     weight             feed       
 Min.   :108.0   casein   :16.90%  
 1st Qu.:204.5   horsebean:14.08%  
 Median :258.0   linseed  :16.90%  
 Mean   :261.3   meatmeal :15.49%  
 3rd Qu.:323.5   soybean  :19.72%  
 Max.   :423.0   sunflower:16.90%
Hide some coefficients in regression summary while still returning call, r-squared and other summary output

Hide some coefficients in regression summary while still returning call, r-squared and other summary output


By : Steve Wonser
Date : March 29 2020, 07:55 AM
To fix this issue You can select the coefficients you want with a slight modification to the print.summary.lm function, which is the internal function that R uses to output the summary results for a summary.lm object.
First, get the code for the function as follows:
code :
getAnywhere(print.summary.lm)
m1 = lm(mpg ~ wt + hp + cyl + vs + am, data=mtcars)
summary(m1)
Call:
  lm(formula = mpg ~ wt + hp + cyl + vs + am, data = mtcars)

Residuals:
    Min      1Q  Median      3Q     Max 
-3.6729 -1.6583 -0.4297  1.3307  5.4688 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 33.24160    5.48527   6.060 2.11e-06 ***
wt          -2.54332    0.93506  -2.720   0.0115 *  
hp          -0.02589    0.01387  -1.866   0.0733 .  
cyl         -0.40179    0.79364  -0.506   0.6169    
vs           1.17067    1.81283   0.646   0.5241    
am           1.97575    1.64825   1.199   0.2415    
---
  Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 2.537 on 26 degrees of freedom
Multiple R-squared:  0.8514,  Adjusted R-squared:  0.8228 
F-statistic:  29.8 on 5 and 26 DF,  p-value: 5.571e-10
my.summary.lm(summary(m1), my.rows=2:4)
my.summary.lm(summary(m1), my.rows=grep("wt|hp|cyl", names(coef(m1))))
Call:
  lm(formula = mpg ~ wt + hp + cyl + vs + am, data = mtcars)

Residuals:
    Min      1Q  Median      3Q     Max 
-3.6729 -1.6583 -0.4297  1.3307  5.4688 

Coefficients:
    Estimate Std. Error t value Pr(>|t|)  
wt  -2.54332    0.93506  -2.720   0.0115 *
hp  -0.02589    0.01387  -1.866   0.0733 .
cyl -0.40179    0.79364  -0.506   0.6169  
---
  Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 2.537 on 26 degrees of freedom
Multiple R-squared:  0.8514,  Adjusted R-squared:  0.8228 
F-statistic:  29.8 on 5 and 26 DF,  p-value: 5.571e-10
my.summary.lm = function (x, digits = max(3L, getOption("digits") - 3L), 
                       symbolic.cor = x$symbolic.cor, 
                       signif.stars = getOption("show.signif.stars"), 
                       my.rows, ...)                     # NOTE NEW my.rows ARGUMENT
{
  cat("\nCall:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"), 
      "\n\n", sep = "")
  resid <- x$residuals
  df <- x$df
  rdf <- df[2L]
  cat(if (!is.null(x$weights) && diff(range(x$weights))) 
    "Weighted ", "Residuals:\n", sep = "")
  if (rdf > 5L) {
    nam <- c("Min", "1Q", "Median", "3Q", "Max")
    rq <- if (length(dim(resid)) == 2L) 
      structure(apply(t(resid), 1L, quantile), dimnames = list(nam, 
                                                               dimnames(resid)[[2L]]))
    else {
      zz <- zapsmall(quantile(resid), digits + 1L)
      structure(zz, names = nam)
    }
    print(rq, digits = digits, ...)
  }
  else if (rdf > 0L) {
    print(resid, digits = digits, ...)
  }
  else {
    cat("ALL", df[1L], "residuals are 0: no residual degrees of freedom!")
    cat("\n")
  }
  if (length(x$aliased) == 0L) {
    cat("\nNo Coefficients\n")
  }
  else {
    if (nsingular <- df[3L] - df[1L]) 
      cat("\nCoefficients: (", nsingular, " not defined because of singularities)\n", 
          sep = "")
    else cat("\nCoefficients:\n")
    coefs <- x$coefficients[my.rows,]                      # SUBSET my.rows
    if (!is.null(aliased <- x$aliased) && any(aliased)) {
      cn <- names(aliased)
      coefs <- matrix(NA, length(aliased), 4, dimnames = list(cn, 
                                                              colnames(coefs)))
      coefs[!aliased, ] <- x$coefficients
    }
    printCoefmat(coefs, digits = digits, signif.stars = signif.stars, 
                 na.print = "NA", ...)
  }
  cat("\nResidual standard error:", format(signif(x$sigma, 
                                                  digits)), "on", rdf, "degrees of freedom")
  cat("\n")
  if (nzchar(mess <- naprint(x$na.action))) 
    cat("  (", mess, ")\n", sep = "")
  if (!is.null(x$fstatistic)) {
    cat("Multiple R-squared: ", formatC(x$r.squared, digits = digits))
    cat(",\tAdjusted R-squared: ", formatC(x$adj.r.squared, 
                                           digits = digits), "\nF-statistic:", formatC(x$fstatistic[1L], 
                                                                                       digits = digits), "on", x$fstatistic[2L], "and", 
        x$fstatistic[3L], "DF,  p-value:", format.pval(pf(x$fstatistic[1L], 
                                                          x$fstatistic[2L], x$fstatistic[3L], lower.tail = FALSE), 
                                                       digits = digits))
    cat("\n")
  }
  correl <- x$correlation
  if (!is.null(correl)) {
    p <- NCOL(correl)
    if (p > 1L) {
      cat("\nCorrelation of Coefficients:\n")
      if (is.logical(symbolic.cor) && symbolic.cor) {
        print(symnum(correl, abbr.colnames = NULL))
      }
      else {
        correl <- format(round(correl, 2), nsmall = 2, 
                         digits = digits)
        correl[!lower.tri(correl)] <- ""
        print(correl[-1, -p, drop = FALSE], quote = FALSE)
      }
    }
  }
  cat("\n")
  invisible(x)
}
# lm object
m1 = lm(mpg ~ wt + hp + cyl + vs + am, data=mtcars)

# plm object
library(plm)

# Example from plm help
data("Produc", package = "plm")
zz <- plm(log(gsp) ~ log(pcap) + log(pc) + log(emp) + unemp,
          data = Produc, index = c("state","year"))
# Summary function that allows selection of which coefficients to include 
# in the coefficient table
# Works with summary.lm and summary.plm objects
my.summary = function(x, rows, digits=3) {

  # Print a few summary elements that are common to both lm and plm model summary objects
  cat("Call\n")
  print(x$call)
  cat("\nResiduals\n")
  print(summary(x$residuals))
  cat("\n")
  print(coef(x)[rows,])

  # Print elements unique to lm model summary objects
  if("summary.lm" %in% class(x)) {
    cat("\nResidual standard error:", round(x$sigma,3), "on", x$df[2], "degrees of freedom")
    cat(paste(c("\nF-statistic:", " on"," and"), round(x$fstatistic,2), collapse=""),
        "DF, p-value:",
        format.pval(pf(x$fstatistic[1L], x$fstatistic[2L], x$fstatistic[3L], 
                       lower.tail = FALSE), digits=digits))

  # Print elements unique to plm model summary objects  
  } else if ("summary.plm" %in% class(x)) {
    cat(paste("\nResidual Sum of Squares: ", signif(deviance(x), 
                                                  digits), "\n", sep = ""))
    fstat <- x$fstatistic
    if (names(fstat$statistic) == "F") {
      cat(paste("F-statistic: ", signif(fstat$statistic), " on ", 
                fstat$parameter["df1"], " and ", fstat$parameter["df2"], 
                " DF, p-value: ", format.pval(fstat$p.value, digits = digits), 
                "\n", sep = ""))
    }
    else {
      cat(paste("Chisq: ", signif(fstat$statistic), " on ", 
                fstat$parameter, " DF, p-value: ", format.pval(fstat$p.value, 
                                                               digits = digits), "\n", sep = ""))
    }
  }
}
my.summary(summary(m1), 2:4)
Call
lm(formula = mpg ~ wt + hp + cyl + vs + am, data = mtcars)

Residuals
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
-3.6730 -1.6580 -0.4297  0.0000  1.3310  5.4690 

       Estimate Std. Error    t value   Pr(>|t|)
wt  -2.54331718 0.93506164 -2.7199460 0.01148231
hp  -0.02588661 0.01387176 -1.8661377 0.07334148
cyl -0.40178727 0.79364098 -0.5062582 0.61694148

Residual standard error: 2.537 on 26 degrees of freedom
F-statistic: 29.8 on 5 and 26 DF, p-value: 5.57e-10
my.summary(summary(zz), 2:3)
Call
plm(formula = log(gsp) ~ log(pcap) + log(pc) + log(emp) + unemp, 
    data = Produc, index = c("state", "year"))

Residuals
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
-0.120500 -0.023740 -0.002041  0.000000  0.018140  0.174700 

          Estimate Std. Error  t-value      Pr(>|t|)
log(pc)  0.2920069 0.02511967 11.62463  7.075069e-29
log(emp) 0.7681595 0.03009174 25.52725 2.021455e-104

Residual Sum of Squares: 1.11
F-statistic: 3064.81 on 4 and 764 DF, p-value: <2e-16
How to restructure javascript functions to output data in different function

How to restructure javascript functions to output data in different function


By : jiaofj
Date : March 29 2020, 07:55 AM
To fix the issue you can do I'm wondering if you can help me. I have some code that works that I have been trying to restructure. This is how it looks now: , I believe your problem resides here:
code :
getReport(r1.reportID, "get").done(r2=>reportHandler(r1.reportID, r2, 0))
getReport(r1.reportId, "get").done((r2) => { reportHandler(r1.reportId, r2, 0); });
const r2 = await getReport(r1.reportId, "get");
const handler = await reportHandler(r1.reportId, r2, 0);
// and so on
function myfunction(ref) {
  getReport(ref, "queue", "hour", "2018-09-03", "2018-10-04", "pageviews", "page").done(function(r1) {
    getReport(r1.reportId, "get").done((r2) => {
      reportHandler(r1.reportId, r2, 0);
    });
  });
}
Related Posts Related Posts :
  • get first entries in rows of list?
  • Conditionally removing rows from a matrix in R
  • Using a loop to find P(-1.5<Y<1.5) for a range of sample sizes
  • R-Count and list the maximum count row by row
  • Include Iverson Bracket in R documentation
  • update a data frame and environment in R
  • How to write dynamic cumulative multiple in R
  • format time using as.POSIX in R
  • Change the class of multiple columns
  • Remove period and spaces within column headings nested in a list of data frames
  • R: error message --- package error: "functionName" not resolved from current namespace
  • labels with geom_text ggplot2
  • Passing mongodb ISODate in R
  • Importing "csv" file with multiple-character separator to R?
  • Change row names of a table obtained from a lm regression using xtable function
  • R language iterate over R object
  • How do you delete the header in a dataframe?
  • Re coding in R using complicated statement
  • accumulating functions and closures in R
  • How do you combine two columns into a new column in a dataframe made of two or more different csv files?
  • Twitter authentication fails
  • Summing Values of One Vector Conditional on Values of Another Vector
  • draw cube into 3D scatterplot in RGL
  • lme4 translate formula to code in 3-level model
  • How to draw single axis plot in R
  • Combine geom_tile() and facet_grid/facet_wrap and remove space between tiles (ggplot2)
  • Use snpStats with R version 3.0.1
  • Makefile gives strange error while compiling markdown file into .docx file
  • How to determine whether a points lies in an ellipse
  • Summarize data already grouped in r
  • Is the bigvis package for R not available for R version 3.0.1?
  • Operator overloading in R reference classes
  • How to enable user to switch between ggplot2 and gVis graphs in R Shiny?
  • Is there an easy way to separate categorical vs continuous variables into two dataset in R
  • Correct previous year by id within R
  • Installation of rdyncall package for R
  • ggplot2 plot that evaluates the percentage and mean of a third variable at intersecting points
  • Error Handling with Lapply
  • data.table - split multiple columns
  • How to compute the overall mean for several files in R?
  • R: Graph Plotting: Subscripts in the legend like LaTeX
  • Restructuring data in R
  • Distance of pointsfrom cluster centers after K means clustering
  • R incorrect value of date function
  • Package "Imports" not loading in R development package
  • r - run a user defined function several times by taking column elements as parameters
  • Create input$selection to subset data AND radiobuttons to choose plot type in Shiny
  • Generate crosstabulations from dataframe of categorical variables in survey
  • New behavior in data.table? .N / something with `by` (calculate proportion)
  • search certain number vector in R
  • R version doesn't support quartz graphic device - RStudio won't plot
  • Referencing a function parameter in R
  • How to synchronize signals using a cross-correlation and FFT in R?
  • Plotting coefficients and corresponding confidence intervals
  • passing expressions to curve() within a function
  • More effective merging of matched column with duplicates in data.table
  • Easy way to export multiple data.frame to multiple Excel worksheets
  • R Foreach Iterator - Walkforward
  • Table format and output in R
  • Restructuring data and duplicating rows in R
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org