我必须从130个不同的.txt文件中提取出文件,以计算每年给定名称的比例。我的程序正确执行了计算,但是当它循环到下一个文件时,出现此错误:
文件(文件“ rt”)中的错误:无效的“描述”参数
baby = function(name, sex, data) {
all.files = dir(path = data, pattern = ".txt")
#print(all.files)
proportion = vector()
i = 1
for(file in all.files ){
direc = paste0(data, "/", file)
data = read.csv(direc, sep = ",", header = FALSE)
#print(data)
name.row = which(data[,1] == name)
print(name.row)
if(data[name.row[1],2] == sex) {
#print("hit")
name.count = data[name.row[1],3]
# print(name.count)
}
if (data[name.row[2],2] == sex) {
#print("miss")
name.count = data[name.row[2],3]
# print(name.count)
}
print(name.count)
total.count = sum(data[,3])
# print(total.count)
proportion[i] = name.count / total.count
print(proportion)
i = i + 1
}
return(proportion)
}
它应该返回比例向量,每个文件一个,而不是我只浏览一个文件
答案 0 :(得分:0)
您可以使用sapply执行您的工作。这样的事情可能会起作用:
sapply(list.files(path = "your_directory",
pattern = ".txt",
full.names = TRUE),
your_fun)
编辑:对此source的赠送金额。