【发布时间】: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