2016-03-24 1 views
0

Here's einen Auszug der XML-Datei. Ich habe herausgefunden, wie man alle Fragen, alle richtigen Antworten und alle falschen Antworten in einer Spalte zusammenfasst. Dies ist der Code, den ich verwendet habe:Erstellen Sie neue Spalten für jede Frage in XML-Datei mit R

#loads package 
library(XML) 
xmlfile=xmlTreeParse("cowen.xml") 
class(xmlfile) 
xmltop = xmlRoot(xmlfile) #gives content of root 

#Gets all the Questions 
Questions = sapply(getNodeSet(xmltop,"//quiz/question/name/text"), function(x) xmlSApply(x, xmlValue)) 
#dataframe of questions 
Q = as.data.frame(Questions) 

#Gets All the corrects answers 
CorrectAnswers = sapply(getNodeSet(xmltop ,"//quiz/question/answer[@fraction='100']/text"), function(x) xmlSApply(x, xmlValue)) 
#dataframe of correct answers 
CA = as.data.frame(CorrectAnswers) 

#Gets all the wrong answers (But it doesnt get it by each question) 
WrongAnswers = sapply(getNodeSet(xmltop,"//quiz/question/answer[@fraction='0']/text"), function(x) xmlSApply(x, xmlValue)) 
#dataframe of wrong answers 
WA = as.data.frame(WrongAnswers) 

Ich möchte einen Datensatz mit vier Spalten erstellen. Spalte 1 hat die Frage, Spalte 2 hat die richtige Antwort und Spalte 3-5 hat die falschen Antworten. Ich bin mir nicht sicher, wie man eine Schleife/Funktion erstellt, die jeden Knoten durchläuft und nur die falsche Antwort erhält und dann drei Spalten mit jeder falschen Antwort erzeugt. In der XML-Datei:
<answer fraction="100"> stellt eine richtige Antwort und <answer fraction="0"> eine falsche Antwort darstellt.

Antwort

1

Ich würde nur Funktionen auf die gleichen getNodeSet anwenden.

doc <- xmlParse("file.xml") 
q1 <- getNodeSet(doc, "//question[@type='multichoice']") 

Q <- sapply(q1, function(x) xpathSApply(x, "./name/text", xmlValue)) 
CA <- sapply(q1, function(x) xpathSApply(x, "./answer[@fraction='100']/text", xmlValue)) 
WA <- sapply(q1, function(x) xpathSApply(x, "./answer[@fraction='0']/text", xmlValue)) 

data.frame(Q, CA, t(WA)) 
+0

Vielen Dank. Das hat wirklich gut funktioniert! –