【问题标题】:Debugging user-defined function调试用户自定义函数
【发布时间】:2013-01-24 15:28:51
【问题描述】:

对于“Baltimore homicides”的数据集 需要创建一个函数,该函数接受一个字符串,例如 "shooting" 并返回一个整数,表示“shooting”受害者的数量。 我编写了以下函数,但收到错误

错误:“}”中出现意外的“}”

错误:找不到对象“counti”

我也不知道 ==Null 是否正确

count <- function(cause = NULL) {

## Check that "cause" is non-NULL; else throw error
if cause==NULL
{
stop()
print("no cause provided")
}

## Read "homicides.txt" data file
homicides <- readLines("homicides.txt")
## Extract causes of death
i <- grep(cause, homicides)  ##get indices of cause
counti <- lenghth(i) ##get count of indices
## Check that specific "cause" is allowed; else throw error
if counti=0
{
stop()
print("no such cause")
}

## Return integer containing count of homicides for that cause      
return(counti)  
}

这是我编辑后的工作功能,谢谢大家

count <- function(cause = NULL) {
  if(missing(cause) | is.null(cause)) stop("no cause provided")
  homicides <- readLines("homicides.txt")
  i=length(grep(cause, homicides))
  if(i==0) stop("no cause found")
  return(i)
  }

【问题讨论】:

  • 至少,您在 if 语句周围缺少括号,并且您使用的是 == 而不是 is.null
  • @GSee,谢谢。我将相应地编辑我的问题。有没有理由不“找到”counti
  • 另外,stop() 就是这个意思。它永远不会到达下一个print()
  • 你拼错了length()
  • 而你的最后一个if 使用= 而不是==(除了不使用括号)

标签: r


【解决方案1】:

您可以通过这样做将您的功能简化为 2 行:

count <- function(cause = NULL, data) {
  if(is.null(cause)) stop("no cause provided")
  length(grep(cause, data))
}

data <- c("murder", "some other cause")

count("murder", data)
[1] 1

注意以下原则:

  • R 具有函数式语言的许多特性。这意味着每个函数都应尽可能仅依赖于您传递给它的参数。
  • 当您的代码中有错误时,请将其简化为尽可能短的版本,修复错误,然后从那里进行构建。

此外,请保留 stop() 以了解真正致命的错误。在您的数据中找不到搜索字符串不是错误,它只是意味着找不到原因。您不希望您的代码停止。最多发出message()warning()

【讨论】:

  • 应该是||而不是|,而missing()基本上是多余的,因为NULL是默认的
  • @hadley 好点。我编辑了帖子以反映您的明智建议。
猜你喜欢
  • 2012-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多