【发布时间】:2019-11-18 13:22:06
【问题描述】:
有很多具有类似主题的 R 帖子,但它们没有提供我正在寻找的内容。
我想要的伪代码(这不是R)如下:
fileConn <- file("foo.txt")
for (i in 1:hiLimit) {
# extract elements from each nested and variable json element in an R list.
# paste elements into a comma separated list
write(pastedStuff,fileConn)
}
close(fileConn)
现在,如果我跳过“文件”和“关闭”,而只使用带有文件名和“附加=真”的“猫”,如下所示:
cat(paste(cve,vndr,pnm,vnmbr,vaffct,sep=","),file="outfile.txt",append=TRUE,sep="\n")
我得到了我想要的。但是,据推测,这是为每个调用打开和关闭文件(??? 假设)。避免这种情况应该会使其更快。
我无法解决的是如何通过伪代码中的方法实现结果,该方法仅打开和关闭文件一次。使用 'cat' 或 'writeLines' 只会给我文件中的最后一行。
作为解释,我正在处理的问题涉及从头开始逐行构建数据框。我的时间安排(见下文)表明,到目前为止,我能做到这一点的最快方法是将 csv 写入磁盘,然后将其读回以创建数据帧。这很疯狂,但这就是它的发展方式。
## Just the loop without any attempt to collect parsed data into a dataframe
system.time(tmp <- affectsDetails(CVEbase,Affect))
user system elapsed
0.30 0.00 0.29
## Using rbind as in rslt<- rbind (rslt,c(stuff)) to build dataframe in the loop.
system.time(tmp <- affectsDetails(CVEbase,Affect))
user system elapsed
990.46 2.94 994.01
# Preallocate and insert list as per
# https://stackoverflow.com/questions/3642535/creating-an-r-dataframe-row-by-row
system.time(tmp <- affectsDetails(CVEbase,Affect))
user system elapsed
1451.42 0.04 1452.37
# Write to a file with cat and read back the csv.
system.time(tmp <- affectsDetails(CVEbase,Affect))
user system elapsed
10.70 29.00 45.42
任何建议表示赞赏!
【问题讨论】: