Function

コメント・参照等

FUN = f_plotly_add_fitted_line.r
function (lydata, data, col_x = 1, col_y = 2, significant_level = 0.05) 
{
    x <- data[, col_x]
    y <- data[, col_y]
    datadf <- data.frame(x, y)
    n <- nrow(datadf)
    fit <- lm(formula = y ~ x, data = datadf)
    t_value <- qt(1 - significant_level/2, n - 2)
    Sxx <- sum((x - mean(x))^2)
    Sxy <- sum((x - mean(x)) * (y - mean(y)))
    a <- Sxy/Sxx
    b <- mean(y) - mean(x) * a
    estimated_y <- a * x + b
    residuals <- y - estimated_y
    sigma <- sqrt(sum((residuals - mean(residuals))^2)/(n - 2))
    ci <- t_value * sqrt(1/n + ((x - mean(x))^2)/Sxx) * sigma
    lower <- estimated_y - ci
    upper <- estimated_y + ci
    lydata <- lydata %>% add_lines(x = x, y = fitted(fit), line = list(color = "rgb(255,127,80)", width = 2), hoverinfo = "none") %>% add_lines(x = x, y = lower, line = list(color = "rgb(205, 12, 24)", width = 2, dash = "dash"), hoverinfo = "none") %>% add_lines(x = x, y = upper, line = list(color = "rgb(205, 12, 24)", width = 2, dash = "dash"), hoverinfo = "none")
    return(lydata)
}