【发布时间】:2020-10-08 21:31:20
【问题描述】:
我正在从多个适合特定范围的 .txt 文件中汇总数据。某些 txt 文件不包含引发错误的目标值。 (神秘的是,这以前有效,脚本将继续 - 现在它抛出错误Error in data.frame(df, f) : arguments imply differing number of rows: 0, 所以我引入了 tryCatch 将数据中的数据写入丢失的 df。
使用 tryCatch 将零写入临时表,以便以后对其进行计数。输出文件是一个新的 df,其中包含过滤后的值和找到的文件。
#finds the files with the correct extensions
fs <-list.files(path, pattern=glob2rx("*.txt$"))
for (f in fs){
fname <- file.path(path, f)
df <- read_tsv(fname, skip =1,skip_empty_rows = T, col_types="dd", col_names=c("X1","X2"))
#filters the data that finds the target peak within the tolerances
# simple 2 column with rows of filtered data
df<- filter(df,between(X1,mmneg,mmpos))
#create new data based on filtered content
#tryCatch writes in zeros if no data found.. or it doesn't!
tryCatch(
allSpectra <- data.frame(df,f),
error =function(e) {
df2<- rbind(df, list(0,0))
allSpectra <- data.frame(df2,f)
}
)
#write new data to file
write.table(allSpectra,
paste("SearchResults_",mc,"_masstol",tol,"mmu.csv", sep =""),
append= T,
sep=",",
row = F,
col.names = F
)
}
输出:
> Error: object 'allSpectra' not found
当我不在 for(f in fs) 内运行以下命令时,allSpectra 没有问题。我怀疑我的 tryCatch 有错误
df2<- rbind(df, list(0,0))
allSpectra <- data.frame(df2,f)
> allSpectra
X0 X0.1 f
1 0 0 PterocarpusTinctorius_WD161955_Tw313.txt
【问题讨论】:
-
如果它继续循环到下一个文件并创建一个空表,我也会很高兴
-
我认为您使用的是
dplyr(由于between),这意味着filter很可能返回一个data.frame,然后您在另一个我>data.frame。您当时认为df应该是什么?如果问题是可重现的,包括有代表性的样本数据(例如来自dput(head(x))),那么提供帮助会容易得多。 -
@r2evans 我有
conflict_prefer("filter", "dplyr")我会根据您所说的提供线索,清理并解决问题。df是一个临时的data.frame,它保存了来自 txtf的过滤行。在合并到write.table之前 -
是的,
data.frame(data.frame(...), data.frame(...))应该是什么样的? -
谢谢,在下面发布更新作为答案。删除了 df 中凌乱的第二个 df 并调整了 tryCatch