Question

I have created a package named test and I have a function named lad inside it. When I build it and after check it with cran=TRUE, I receive the following error. Any idea what's going wrong?

* checking examples ... ERROR
Running examples in 'test-Ex.R' failed
The error most likely occurred in:

> base::assign(".ptime", proc.time(), pos = "CheckExEnv")
> ### Name: lad
> ### Title: LAD
> ### Aliases: lad
> 
> ### ** Examples
> 
> lad(y = "farm", x = "land", data="http://pages.stat.wisc.edu/~gvludwig/327-5/FarmLandArea.csv")
Error in (function (par)  : object 'sum.abs.dev' not found
Calls: lad -> optim -> <Anonymous>
Execution halted
Error: Command failed (1)

Here's the code inside power.R function which is in the R folder of my test package.

sum.abs.dev<-function(beta,a=land,b=farm)
{
  total<-0
  n<-length(b)
  for (i in 1:n)
  {
    total <- total + abs(b[i]-beta[1]-beta[2]*a[i])
  }
  return(total)
}

#' LAD
#' 
#' Minimize the sum of absolute deviations from the residuals
#' @param y A value showing the first column of the data frame
#' @param x A value showing the second column of the data frame
#' @param data A value showing the link to the data frame in CSV format
#' @return The square of the input
#' @export
#' @examples 
#' lad(y = "farm", x = "land", data="http://pages.stat.wisc.edu/~gvludwig/327-5/FarmLandArea.csv")

lad <- function(y = "farm", x = "land", data="http://pages.stat.wisc.edu/~gvludwig/327-5/FarmLandArea.csv")
{
  library(stats)
  dat <- read.csv(data)
  dat.x <- dat[[x]]
  dat.y <- dat[[y]]
  fit<-lm(dat.y~dat.x)
  beta.out=optim(fit$coefficients,sum.abs.dev)$par

  return(beta.out)
}

Here are the commands I ran so far before check:

build("/Users/mona/test")
build("/Users/mona/test", binary=TRUE)
check("/Users/mona/test", cran=FALSE)

When I click Build & Reload I don't receive any problem and here's what I receive:

> library(test)

Attaching package: ‘test’

The following object is masked _by_ ‘.GlobalEnv’:

    lad

enter image description here

Was it helpful?

Solution

The following achieves what you want, I believe:

lad <- function(y, x, data) {
  dat <- setNames(read.csv(data)[, c(x, y)], c('x', 'y'))
  sum.abs.dev <- function(beta, data) {
    with(data, sum(abs(y - beta[1] - beta[2] * x)))
  }
  fit <- lm(y ~ x, dat)
  optim(par=coef(fit), sum.abs.dev, data=dat)$par
}

lad(y = "farm", x = "land", data="FarmLandArea.csv")

#  (Intercept)            x 
# -605.2293682    0.3642028 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top