R 调试用户定义函数

R 调试用户定义函数,r,R,对于“”的数据集 需要创建一个函数,该函数以字符串为例“shooting”,并返回一个表示“shooting”受害者计数的整数。 我编写了以下函数,但收到错误 错误:“}”中出现意外“}” 错误:找不到对象“counti” 我也不知道==Null是否正确 count <- function(cause = NULL) { ## Check that "cause" is non-NULL; else throw error if cause==NULL { stop(

对于“”的数据集 需要创建一个函数,该函数以字符串为例“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通过执行以下操作,您可以将函数简化为两行:

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

count通过执行以下操作,您可以将函数简化为两行:

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

计数最少,if语句周围缺少括号,您使用的是
=
而不是
is.null
@GSee,谢谢。我将相应地编辑我的问题。有没有理由不“查找”countiAlso,
stop()
就是这个意思。它永远不会到达下一个
print()
。如果
使用
=
而不是
=
(除了不使用括号外),那么你就错了
length()
,你的上一个
如果
使用
=
而不是
,那么你至少会丢失if语句的括号,并且你正在使用
=
而不是
is.null
@GSee,谢谢。我将相应地编辑我的问题。有没有理由不“查找”countiAlso,
stop()
就是这个意思。它将永远不会到达下一个
print()
。如果
使用
=
而不是
=
(除了不使用括号之外),那么你的
长度(
和上一个
拼写错误,并且
缺少()
基本上是冗余的,因为
NULL
是default@hadley说得好。我编辑这篇文章是为了反映你明智的建议。应该是
|
而不是
|
,而且
missing()
基本上是多余的,因为
NULL
是default@hadley说得好。我编辑这篇文章是为了反映你明智的建议。