为什么R中具有函数的拟合值与理想值会有所不同?

时间:2018-06-29 20:41:39

标签: r function regression

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

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

enter image description here

如何实际编写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))

enter image description here

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

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))

enter image description here

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

enter image description here

1 个答案:

答案 0 :(得分:4)

如果我们看一下线条

15:27:21.882 [ERROR] [org.gradle.api.Task] e: C:\Users\diego\Apps\Recorderis\app\build\tmp\kapt3\stubs\debug\tech\destinum\recorderis\DI\AppComponent.java:13: 
error: [Dagger/Nullable] tech.destinum.recorderis.Data.RecorderisDB is not nullable, 
but is being provided by @org.jetbrains.annotations.Nullable @Singleton 
@Provides tech.destinum.recorderis.Data.RecorderisDB 
tech.destinum.recorderis.DI.AppModule.getDB(android.content.Context)
public abstract void inject(@org.jetbrains.annotations.NotNull()
                     ^
  tech.destinum.recorderis.Data.RecorderisDB is injected at
      tech.destinum.recorderis.DI.AppModule.provideDateVM(db)
  tech.destinum.recorderis.Data.ViewModels.DateViewModel is injected at
      tech.destinum.recorderis.activities.Form.dateVM
  tech.destinum.recorderis.activities.Form is injected at
      tech.destinum.recorderis.DI.AppComponent.inject(tech.destinum.recorderis.activities.Form)

您可以看到使用dadosz <- list(A = A, B = B) gridz <- expand.grid(dadosz) gridz[, "fit"] <- f(A, B) 来创建expand.gridA的所有组合,但是在调用B时并没有使用这些值,而是使用了f()A的原始值。你应该已经完成​​

B

这给出了情节

enter image description here