Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

r - Getting unknown error at the end of a for loop - how to fix?

I am running this for loop:

for (i in 1:length(file_list)){

  doc <- read_xml(file_list[i])

  xml_ns(doc)

  ns <- xml_find_all(doc, xpath_person, xml_ns(doc))

  items<-xml_find_all(doc, "//d1:REPORT/d1:People/d1:ACRSPERSON")

  nodenames<-xml_name(xml_children(items))

  contents<-trimws(xml_text(xml_children(items)))

  if (length(items) >0) {

    itemindex<-rep(1:length(items), times=sapply(items, function(x) {length(xml_children(x))}))

    person1<-data.frame(itemindex, nodenames, contents)

    #Convert from long to wide format

    person<- pivot_wider(person1, id_cols= itemindex, names_from = nodenames,

                         values_from = contents)  # %>% unnest(cols = c(A, B, C, D))

    out_person <- rbind.fill(out_person,person )


}

 

However when I run the code all at once (in markdown - feel like it worked in regular rscript) - I get the following error.

**Error in read_xml.character(file_list[i]) : Document is empty [4]**

I tried to add some kind of break but it did not work.

for (i in 1:length(file_list)){

  doc <- read_xml(file_list[i])

  xml_ns(doc)

  ns <- xml_find_all(doc, xpath_person, xml_ns(doc))

  items<-xml_find_all(doc, "//d1:REPORT/d1:People/d1:ACRSPERSON")

  nodenames<-xml_name(xml_children(items))

  contents<-trimws(xml_text(xml_children(items)))

  if (length(items) >0) {

    itemindex<-rep(1:length(items), times=sapply(items, function(x) {length(xml_children(x))}))

    person1<-data.frame(itemindex, nodenames, contents)

    #Convert from long to wide format

    person<- pivot_wider(person1, id_cols= itemindex, names_from = nodenames,

                         values_from = contents)  # %>% unnest(cols = c(A, B, C, D))

    out_person <- rbind.fill(out_person,person )
 if (is.null(file_list[i])){

      break
      }

    }

}

How do I fix this so that the for loop runs correctly. When there are no more items in the file_list the for loop closes successfully. Or is there something else which is causing the problem?

Thanks.

question from:https://stackoverflow.com/questions/65889368/getting-unknown-error-at-the-end-of-a-for-loop-how-to-fix

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...