【问题标题】:Convert summary.lm to JSON将 summary.lm 转换为 JSON
【发布时间】:2018-11-16 21:25:22
【问题描述】:

我正在使用 R 中的管道工运行 R 脚本。我正在尝试从 R 脚本中获取 JSON 响应。但似乎下面的语句输出不支持 JSON 响应。

summary(fm1 <- lm(log(dist) ~ log(speed), data = cars))

我得到以下声明。

Call:
lm(formula = log(dist) ~ log(speed), data = cars)

Residuals:
     Min       1Q   Median       3Q      Max 
-1.00215 -0.24578 -0.02898  0.20717  0.88289 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  -0.7297     0.3758  -1.941   0.0581 .  
log(speed)    1.6024     0.1395  11.484 2.26e-15 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.4053 on 48 degrees of freedom
Multiple R-squared:  0.7331,    Adjusted R-squared:  0.7276 
F-statistic: 131.9 on 1 and 48 DF,  p-value: 2.259e-15

我尝试使用 jsonlite::toJSON,但我想我在某处缺少 R 的基本原理。

我应该怎么做才能将输出转换为我想要的 JSON 结构?

【问题讨论】:

  • 那么想要的输出到底是什么?您希望 JSON 数据如何结构化?我什至无法猜测它会是什么样子,因为 lm 的打印输出不是很结构化。
  • @MrFlick 我想学习如何以通常的方法将其解析为 json。现在,即使我可以将 Min Max 中值作为 json 中的密钥对,对我来说也是双赢。
  • @MrFlick 我是 R 新手,只是尝试运行管道工文章中的上述命令。我想获得表中单列的描述性统计信息。不确定 summary(lm) 是否是答案。但在这种情况下,我可能需要使用它将 R 输出转换为 JSON 格式,这对我来说是金矿
  • 他们可能是jsonlite::toJSON(list(min=min(resid(fm1)), max=max(resid(fm1)), median=median(resid(fm1))), auto_unbox = TRUE)。没有将任意对象转换为 JSON 的“常规”方法。
  • 您可以尝试broom::tidy(或包中的其他功能)以数据框格式获取 lm 的摘要。

标签: r jsonlite plumber


【解决方案1】:

由于您没有提供数据:

ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2, 10, 20, labels = c("Ctl","Trt"))
weight <- c(ctl, trt)
lm.D9 <- lm(weight ~ group)

s <- summary(lm.D9)

这就是^^的样子:

str(s)
## List of 11
##  $ call         : language lm(formula = weight ~ group)
##  $ terms        :Classes 'terms', 'formula'  language weight ~ group
##   .. ..- attr(*, "variables")= language list(weight, group)
##   .. ..- attr(*, "factors")= int [1:2, 1] 0 1
##   .. .. ..- attr(*, "dimnames")=List of 2
##   .. .. .. ..$ : chr [1:2] "weight" "group"
##   .. .. .. ..$ : chr "group"
##   .. ..- attr(*, "term.labels")= chr "group"
##   .. ..- attr(*, "order")= int 1
##   .. ..- attr(*, "intercept")= int 1
##   .. ..- attr(*, "response")= int 1
##   .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv> 
##   .. ..- attr(*, "predvars")= language list(weight, group)
##   .. ..- attr(*, "dataClasses")= Named chr [1:2] "numeric" "factor"
##   .. .. ..- attr(*, "names")= chr [1:2] "weight" "group"
##  $ residuals    : Named num [1:20] -0.862 0.548 0.148 1.078 -0.532 ...
##   ..- attr(*, "names")= chr [1:20] "1" "2" "3" "4" ...
##  $ coefficients : num [1:2, 1:4] 5.032 -0.371 0.22 0.311 22.85 ...
##   ..- attr(*, "dimnames")=List of 2
##   .. ..$ : chr [1:2] "(Intercept)" "groupTrt"
##   .. ..$ : chr [1:4] "Estimate" "Std. Error" "t value" "Pr(>|t|)"
##  $ aliased      : Named logi [1:2] FALSE FALSE
##   ..- attr(*, "names")= chr [1:2] "(Intercept)" "groupTrt"
##  $ sigma        : num 0.696
##  $ df           : int [1:3] 2 18 2
##  $ r.squared    : num 0.0731
##  $ adj.r.squared: num 0.0216
##  $ fstatistic   : Named num [1:3] 1.42 1 18
##   ..- attr(*, "names")= chr [1:3] "value" "numdf" "dendf"
##  $ cov.unscaled : num [1:2, 1:2] 0.1 -0.1 -0.1 0.2
##   ..- attr(*, "dimnames")=List of 2
##   .. ..$ : chr [1:2] "(Intercept)" "groupTrt"
##   .. ..$ : chr [1:2] "(Intercept)" "groupTrt"
##  - attr(*, "class")= chr "summary.lm"

如果您不介意元素分辨率的潜在(在这种情况下是确定的)损失,我们可以完全将任意对象转换为 JSON(您可能在 R基础知识……您缺乏阅读文档的能力?):

jsonlite::toJSON(s, force=TRUE, pretty=TRUE)
## {
##   "call": {},
##   "terms": {},
##   "residuals": [-0.862, 0.548, 0.148, 1.078, -0.532, -0.422, 0.138, -0.502, 0.298, 0.108, 0.149, -0.491, -0.251, -1.071, 1.209, -0.831, 1.369, 0.229, -0.341, 0.029],
##   "coefficients": [
##     [5.032, 0.2202, 22.8501, 9.5471e-15],
##     [-0.371, 0.3114, -1.1913, 0.249]
##   ],
##   "aliased": [false, false],
##   "sigma": [0.6964],
##   "df": [2, 18, 2],
##   "r.squared": [0.0731],
##   "adj.r.squared": [0.0216],
##   "fstatistic": [1.4191, 1, 18],
##   "cov.unscaled": [
##     [0.1, -0.1],
##     [-0.1, 0.2]
##   ]
## } 

如果您需要缺失值,则需要在执行 toJSON() 之前对其进行适当转换

此外,这就是 base:::print.summary.lm 所做的,因此您也可以采用它并制作自己的 JSON:

function (x, digits = max(3L, getOption("digits") - 3L), symbolic.cor = x$symbolic.cor, signif.stars = getOption("show.signif.stars"), ...) {
    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
        if (any(aliased <- x$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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 2012-11-03
    • 2017-03-08
    • 2013-09-18
    • 2011-08-02
    • 2019-08-21
    相关资源
    最近更新 更多