Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中,如何从XML文件中提取两个值,循环5603个文件并写入表_Xml_R_Parsing_Loops - Fatal编程技术网

在R中,如何从XML文件中提取两个值,循环5603个文件并写入表

在R中,如何从XML文件中提取两个值,循环5603个文件并写入表,xml,r,parsing,loops,Xml,R,Parsing,Loops,由于我对R比较陌生,我正在尝试学习如何从XML文件中提取两个值并循环5603个其他值(小,这可能对您有用。我摆脱了for循环,使用了sapply xmlfiles <- list.files(pattern = "*.xml") txtfiles <- gsub("xml", "txt", xmlfiles, fixed = TRUE) 请在运行时告诉我是否有问题。与Richard的方法稍有不同(只是稍有不同)。在将数据写入文件之前,使用ldply制作数据帧。您应该选择his作为答

由于我对R比较陌生,我正在尝试学习如何从XML文件中提取两个值并循环5603个其他值(小,这可能对您有用。我摆脱了
for
循环,使用了
sapply

xmlfiles <- list.files(pattern = "*.xml")
txtfiles <- gsub("xml", "txt", xmlfiles, fixed = TRUE)

请在运行时告诉我是否有问题。

与Richard的方法稍有不同(只是稍有不同)。在将数据写入文件之前,使用
ldply
制作数据帧。您应该选择his作为答案,因为
ldply
函数的“胆量”是他的,但这只是显示了另一种方法(假设您需要一个文件而不是多个文件):

setwd(“XML文件的位置”)

xmlfiles Well
“xmlfiles[i]”
肯定行不通。请尝试使用
粘贴(xmlfiles,sep=“”)创建您的文件名。
hrbrmstr,非常感谢您的评论。使用您的方法,我可以构建一个文件。您的评论帮助我更好地理解其中的内容。谢谢。
xmlfiles <- list.files(pattern = "*.xml")
txtfiles <- gsub("xml", "txt", xmlfiles, fixed = TRUE)
sapply(seq(xmlfiles), function(i){

  doc <- xmlTreeParse(xmlfiles[i], useInternal = TRUE)
  zipcode <- xmlValue(doc[["//ZipCode"]])
  amount <- xmlValue(doc[["//AwardAmount"]])
  DF <- data.frame(zip = zipcode, amount = amount)
  write.table(DF, quote = FALSE, row.names = FALSE, file = txtfiles[i])

})
setwd("LOCATION_OF_XML_FILES")

xmlfiles <- list.files(pattern = "*.xml")

dat <- ldply(seq(xmlfiles), function(i){

  doc <- xmlTreeParse(xmlfiles[i], useInternal = TRUE)

  zipcode <- xmlValue(doc[["//ZipCode"]])
  amount <- xmlValue(doc[["//AwardAmount"]])

  return(data.frame(zip = zipcode, amount = amount))

})

head(dat)
##         zip amount
## 1 442420001  45000
## 2 479072114 400580
## 3 303320420  22050
## 4 326112002  12000
## 5 265066845  37000
## 6 168027000 300000

write.csv(dat, "zipamount.csv", row.names=FALSE)