对于“巴尔的摩凶杀案”数据集,需要创建一个函数,该函数接受一个字符串,例如“射击”,并返回一个整数,表示“射击”的受害者人数。我写了以下函数,但我收到错误
错误:“}”中出现意外的“}”
错误:找不到对象“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)
}