通过R Studio读取函数时未找到对象
当我通过R-Studio运行代码时,我被告知我有一个意外的大括号 我有四个:两个用于打开/关闭函数,两个用于for循环。然后我被告知许多变量都没有找到:意外的“for”,“directory”没有找到,“basedf”没有找到。就好像我的函数没有被识别出来 我试着直接将函数剪切粘贴到控制台中,但出现了类似的错误 是我的功能有缺陷,还是其他问题通过R Studio读取函数时未找到对象,r,syntax-error,curly-braces,R,Syntax Error,Curly Braces,当我通过R-Studio运行代码时,我被告知我有一个意外的大括号 我有四个:两个用于打开/关闭函数,两个用于for循环。然后我被告知许多变量都没有找到:意外的“for”,“directory”没有找到,“basedf”没有找到。就好像我的函数没有被识别出来 我试着直接将函数剪切粘贴到控制台中,但出现了类似的错误 是我的功能有缺陷,还是其他问题 pollutantmean <- function(directory, pollutant, id = 1:332) { files &l
pollutantmean <- function(directory, pollutant, id = 1:332) {
files <- list.files(directory)
subsetFiles <- files[id]
basedf <- data.frame(Date = as.Date(character(),
sulfate = numeric(),
nitrate = numeric(),
ID = numeric())
for (i in subsetFiles) {
filepaths <- paste(directory,"/",i, sep='')
basedf <- rbind(basedf, read.csv(filepaths))
}
good <- complete.cases(basedf)
data2 <- basedf[good,pollutant]
mean(data2)
}
pollutanmean您只是缺少了basedf中的一个括号
:
basedf <- data.frame(Date = as.Date(character(),
sulfate = numeric(),
nitrate = numeric(),
ID = numeric()))
basedf实际上,它应该是:
basedf <- data.frame(Date = as.Date(character()),
sulfate = numeric(),
nitrate = numeric(),
ID = numeric())
非常感谢你在《泰晤士报》结束时接受采访。不知道在R中是否有一种方法可以帮助调试这样的语法,而不是转移我注意力的标准错误消息。我假设您在出现意外的大括号错误之前,在:…
中得到了错误error:unexpected'for'。根据我的经验,如果出现错误:意外…
通常意味着缺少括号、大括号、引号等的匹配项。此外,Rstudio有一些内置调试工具:,但我不确定它们是否有帮助,由于我从未使用过它们,再次感谢您对我的函数@Doug Firr提供的指针和额外的注意事项:请参阅下面的答案,查找缺少的括号。您可以使用list.files(directory,full.names=TRUE)
保存一些步骤。我想你需要一些[i]
在里面。谢谢你的提示@RichardScriven。不过我现在正在学爬
R:> basedf <- data.frame(Date = as.Date(character(), format='%Y/%m/%d'),
sulfate = numeric(),
nitrate = numeric(),
ID = numeric())
R:> basedf
[1] Date sulfate nitrate ID
<0 rows> (or 0-length row.names)