【问题标题】:Why fitted values with function in R get different values from the ideal?为什么 R 中的函数拟合值与理想值不同?
【发布时间】:2018-12-09 02:03:06
【问题描述】:

在测试函数以计算一些回归值时,我注意到function 预测的值与应有的不同。当我以另一种方式执行值的拟合时,我得到了正确的值。

  • 我的回归方程(A=x1;B=x2):

我如何实际编写f 函数来正确计算值?

function我的代码:

A = seq(5, 8, 0.2)
B = seq(30, 70, length.out = length(A))

f <- function(A,B) 281.5786111-39.2014931*A-2.9013646*B+0.5666979*A*B

dadosz <- list(A = A, B = B)
gridz <- expand.grid(dadosz)
gridz[, "fit"] <- f(A, B)

library(lattice)
wireframe(fit ~ A * B, data = gridz,
      panel.aspect = 0.5,
      zoom = 0.8,
      screen = list(z = 215, x = -60),
      scales=list(arrows = FALSE),
      drape = TRUE, 
      col.regions = heat.colors(100, alpha = 1))

使用包和数据操作来完成相同的工作,但目标是使代码可重现。请注意,此处拟合的值是正确的。

library(dplyr)
library(purrr)
library(broom)

term <- c("(Intercept)", "A", "B", "A:B")
estimate <- c(281.5786111, -39.2014931, -2.9013646, 0.5666979)
std.error <- c(58.35909505, 7.47207607, 0.63829627, 0.05755324)
statistic <- c(4.824931, -5.246399, -4.545483, 9.846500)
p.value <- c(1.583042e-04, 6.565454e-05, 2.865084e-04, 1.941398e-08)

coe <- data.frame(term, estimate, std.error, statistic, p.value)

exp <- expand.grid(A = A, B = B) %>% 
  mutate(bo = as.numeric(1)) %>% 
  mutate(ult = A*B) %>% 
  select(bo, A, B, ult) %>% 
  as.matrix()

m_beta <- coe$estimate
reg <- t(m_beta %*% t(exp)) 
exp <- cbind(exp, reg) %>% 
  as.data.frame() %>% 
  rename(reg = V5)

wireframe(reg ~ A * B, data = exp,
      panel.aspect = 0.5,
      zoom = 0.8,
      screen = list(z = 310, x = -70),
      scales=list(arrows = FALSE),
      drape = TRUE, 
      col.regions = heat.colors(100, alpha = 1))

由于我有疑问,我在 Excel 和 internet site 上对其进行了测试,并再次检查错误在 function 中。

【问题讨论】:

    标签: r function regression


    【解决方案1】:

    如果我们看线条

    dadosz <- list(A = A, B = B)
    gridz <- expand.grid(dadosz)
    gridz[, "fit"] <- f(A, B)
    

    可以看到 use 使用了expand.grid 来创建AB 的所有组合,但是在调用f() 时没有使用这些值,而是使用了A 的原始值和B。你应该做的

    gridz[, "fit"] <- f(gridz$A, gridz$B)
    

    这给出了情节

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-28
      • 2020-01-28
      • 1970-01-01
      • 2013-05-15
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      相关资源
      最近更新 更多