### **例子...错误:无法找到一个R函数建筑包(### ** Examples … Error

2019-10-20 01:34发布

我创建了一个名为封装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)

当我点击构建与刷新我没有收到任何的问题,这是我得到:

> library(test)

Attaching package: ‘test’

The following object is masked _by_ ‘.GlobalEnv’:

    lad

Answer 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 


文章来源: ### ** Examples … Error: could not find function building packages in R