2016-03-24 4 views
0

Here'sを使用して作成します。私はすべての質問、すべての正解、およびすべての間違った答えの列を作る方法を考え出しました。これは私が使用したコードです:XMLファイル内の各Q'uestionの新しい列を、XMLファイルの抜粋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) 

私は4つの列でデータセットを作成したいと思います。列1には質問があり、列2には正解があり、列3-5には正しくない回答があります。私はどのように各ノードを通過し、間違った答えを取得し、各誤った答えの3つの列を作成するループ/関数を作成するか分からない。 XMLファイル:
<answer fraction="100">は正解を表し、 <answer fraction="0">は間違った答えを表します。

答えて

1

私は関数を同じgetNodeSetに適用するだけです。

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

ありがとうございました。これは本当にうまくいった! –