1

我创建了一个名为的包test,其中有一个名为的函数lad。当我构建它并使用 进行检查后cran=TRUE,我收到以下错误。知道出了什么问题吗?

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

这是我包power.R的 R 文件夹中的函数内部代码。test

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

以下是我在检查之前运行的命令:

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

当我单击 Build & Reload 时,我没有收到任何问题,这是我收到的内容:

> library(test)

Attaching package: ‘test’

The following object is masked _by_ ‘.GlobalEnv’:

    lad

在此处输入图像描述

4

1 回答 1

1

我相信以下实现了你想要的:

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 
于 2014-05-02T02:18:52.927 回答