km5*_*041 5 xml memory-management r large-files xml-parsing
基于上一个问题(请参阅此处),我尝试通过 xmlEventParse 读取许多大型 xml 文件,同时保存节点变化的数据。使用此示例 xml: https: //www.nlm.nih.gov/databases/dtd/medsamp2015.xml。
下面的代码使用 xpathSapply 提取必要的值,并使用一系列 if 语句以将唯一值 (PMID) 与记录中的每个非唯一值 (LastName) 相匹配的方式组合这些值 - 对于这些值,可能存在没有姓氏。目标是一路写入一系列小的 csv(此处为每 1000 个姓氏之后),以最大限度地减少内存使用量。
当在全尺寸数据集上运行时,代码成功批量输出文件,但是某些内容仍然存储在内存中,一旦使用所有 RAM,最终会导致系统错误。我在代码运行时观察了任务管理器,并且可以看到 R 的内存随着程序的进展而增长。如果我在运行中停止程序,然后清除 R 工作区(包括隐藏项目),则内存似乎仍被 R 使用。直到我关闭 R 后,内存才会再次释放。
自己运行几次,即使在清除工作区之后,您也会发现 R 的内存使用量仍在增长。
请帮忙!对于以这种方式读取大型 XML 文件的其他人来说,此问题似乎很常见(请参阅此问题中的示例注释)。
我的代码如下:
library(XML)
filename <- "~/Desktop/medsamp2015.xml"
tempdat <- data.frame(pmid=as.numeric(),
lname=character(),
stringsAsFactors=FALSE)
cnt <- 1
branchFunction <- function() {
func <- function(x, ...) {
v1 <- xpathSApply(x, path = "//PMID", xmlValue)
v2 <- xpathSApply(x, path = "//Author/LastName", xmlValue)
print(cbind(c(rep(v1,length(v2))), v2))
#below is where I store/write the temp data along the way
#but even without doing this, memory is used (even after clearing)
tempdat <<- rbind(tempdat,cbind(c(rep(v1,length(v2))), v2))
if (nrow(tempdat) > 1000){
outname <- paste0("~/Desktop/outfiles",cnt,".csv")
write.csv(tempdat, outname , row.names = F)
tempdat <<- data.frame(pmid=as.numeric(),
lname=character(),
stringsAsFactors=FALSE)
cnt <<- cnt+1
}
}
list(MedlineCitation = func)
}
myfunctions <- branchFunction()
#RUN
xmlEventParse(
file = filename,
handlers = NULL,
branches = myfunctions
)
Run Code Online (Sandbox Code Playgroud)
这是一个示例,我们有一个启动脚本invoke.sh,它调用 R 脚本并传递 url 和文件名作为参数...在这种情况下,我之前下载了测试文件medsamp2015.xml并将其放入./data目录中。
invoke.sh脚本中创建一个循环并迭代目标文件名列表。对于调用 R 实例的每个文件,下载它、处理该文件并继续处理下一个。警告:我没有针对任何其他下载文件和格式检查或更改您的功能。我将通过删除第 62 行上的 print() 包装来关闭输出的打印。
print( cbind(c(rep(v1, length(v2))), v2))
Run Code Online (Sandbox Code Playgroud)
.csv文件放置在./data目录中。注意:这是我之前就该主题提供的答案的衍生: R memory notreleased in Windows。我希望它能通过示例有所帮助。
1 #!/usr/local/bin/bash -x
2
3 R --no-save -q --slave < ./47162861.R --args "https://www.nlm.nih.gov/databases/dtd" "medsamp2015.xml"
Run Code Online (Sandbox Code Playgroud)
47162861.R# Set working directory
projectDir <- "~/dev/stackoverflow/47162861"
setwd(projectDir)
# -----------------------------------------------------------------------------
# Load required Packages...
requiredPackages <- c("XML")
ipak <- function(pkg) {
new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if (length(new.pkg))
install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}
ipak(requiredPackages)
# -----------------------------------------------------------------------------
# Load required Files
# trailingOnly=TRUE means that only your arguments are returned
args <- commandArgs(trailingOnly = TRUE)
if ( length(args) != 0 ) {
dataDir <- file.path(projectDir,"data")
fileUrl = args[1]
fileName = args[2]
} else {
dataDir <- file.path(projectDir,"data")
fileUrl <- "https://www.nlm.nih.gov/databases/dtd"
fileName <- "medsamp2015.xml"
}
# -----------------------------------------------------------------------------
# Download file
# Does the directory Exist? If it does'nt create it
if (!file.exists(dataDir)) {
dir.create(dataDir)
}
# Now we check if we have downloaded the data already if not we download it
if (!file.exists(file.path(dataDir, fileName))) {
download.file(fileUrl, file.path(dataDir, fileName), method = "wget")
}
# -----------------------------------------------------------------------------
# Now we extrat the data
tempdat <- data.frame(pmid = as.numeric(), lname = character(),
stringsAsFactors = FALSE)
cnt <- 1
branchFunction <- function() {
func <- function(x, ...) {
v1 <- xpathSApply(x, path = "//PMID", xmlValue)
v2 <- xpathSApply(x, path = "//Author/LastName", xmlValue)
print(cbind(c(rep(v1, length(v2))), v2))
# below is where I store/write the temp data along the way
# but even without doing this, memory is used (even after
# clearing)
tempdat <<- rbind(tempdat, cbind(c(rep(v1, length(v2))),
v2))
if (nrow(tempdat) > 1000) {
outname <- file.path(dataDir, paste0(cnt, ".csv")) # Create FileName
write.csv(tempdat, outname, row.names = F) # Write File to created directory
tempdat <<- data.frame(pmid = as.numeric(), lname = character(),
stringsAsFactors = FALSE)
cnt <<- cnt + 1
}
}
list(MedlineCitation = func)
}
myfunctions <- branchFunction()
# -----------------------------------------------------------------------------
# RUN
xmlEventParse(file = file.path(dataDir, fileName),
handlers = NULL,
branches = myfunctions)
Run Code Online (Sandbox Code Playgroud)
〜/dev/stackoverflow/47162861/data/medsamp2015.xml
$ ll
total 2128
drwxr-xr-x@ 7 hidden staff 238B Nov 10 11:05 .
drwxr-xr-x@ 9 hidden staff 306B Nov 10 11:11 ..
-rw-r--r--@ 1 hidden staff 32K Nov 10 11:12 1.csv
-rw-r--r--@ 1 hidden staff 20K Nov 10 11:12 2.csv
-rw-r--r--@ 1 hidden staff 23K Nov 10 11:12 3.csv
-rw-r--r--@ 1 hidden staff 37K Nov 10 11:12 4.csv
-rw-r--r--@ 1 hidden staff 942K Nov 10 11:05 medsamp2015.xml
Run Code Online (Sandbox Code Playgroud)
> ./invoke.sh > runtime.txt
+ R --no-save -q --slave --args https://www.nlm.nih.gov/databases/dtd medsamp2015.xml
Loading required package: XML
Run Code Online (Sandbox Code Playgroud)
文件:运行时.txt