library(mosaicCalc)
## Loading required package: mosaic
## Registered S3 method overwritten by 'mosaic':
##   method                           from   
##   fortify.SpatialPolygonsDataFrame ggplot2
## 
## The 'mosaic' package masks several functions from core packages in order to add 
## additional features.  The original behavior of these functions should not be affected by this.
## 
## Attaching package: 'mosaic'
## The following objects are masked from 'package:dplyr':
## 
##     count, do, tally
## The following object is masked from 'package:Matrix':
## 
##     mean
## The following object is masked from 'package:ggplot2':
## 
##     stat
## The following objects are masked from 'package:stats':
## 
##     binom.test, cor, cor.test, cov, fivenum, IQR, median, prop.test,
##     quantile, sd, t.test, var
## The following objects are masked from 'package:base':
## 
##     max, mean, min, prod, range, sample, sum
## Loading required package: mosaicCore
## 
## Attaching package: 'mosaicCore'
## The following objects are masked from 'package:dplyr':
## 
##     count, tally
## 
## Attaching package: 'mosaicCalc'
## The following object is masked from 'package:stats':
## 
##     D
Families <- read.csv("http://www.mosaic-web.org/go/datasets/Income-Housing.csv")
gf_point(TwoVehicles ~ Income, data = Families)

kguess <- log(0.5) / 25000
kguess
## [1] -2.772589e-05
library(mosaic)

project( TwoVehicles ~ 1 + exp(Income*kguess), data = Families)
##          (Intercept) exp(Income * kguess) 
##             110.4263            -101.5666
library(mosaicCalc)
f <- makeFun( 110.43 - 101.57*exp(Income * k) ~ Income, k = kguess)
gf_point(TwoVehicles ~ Income, data = Families) %>%
  slice_plot(f(Income) ~ Income) 

f(Income = 10000)
## [1] 33.45433
f(Income = 50000)
## [1] 85.0375
Results <- Families %>% 
  dplyr::select(Income, TwoVehicles) %>%
  mutate(model_val = f(Income = Income),
         resids = TwoVehicles - model_val)
Results
##   Income TwoVehicles model_val     resids
## 1   3914        17.3  19.30528 -2.0052822
## 2  10817        34.3  35.17839 -0.8783904
## 3  21097        56.4  53.84097  2.5590313
## 4  34548        75.3  71.45680  3.8432013
## 5  51941        86.6  86.36790  0.2320981
## 6  72079        92.9  96.66273 -3.7627306
sum(Results$resids^2)
## [1] 40.32358
sum_square_resids <- Vectorize(function(k) {
  sum((Families$TwoVehicles - f(Income=Families$Income, k)) ^ 2)
})
slice_plot(
   sum_square_resids(k) ~ k, 
   domain(k = range(log(0.5)/40000,log(0.5)/20000)))