2016-03-24 19 views
0

Here's kullanarak yeni sütunlar oluşturun. Tüm soruların bir sütununu, tüm doğru cevapları ve tüm yanlış cevapları nasıl yapacağımı anladım. Kullandığım kod:XML dosyasındaki her bir Q'uestion için, XML dosyasının bir alıntıını 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) 

Dört sütunlu bir veri kümesi oluşturmak istiyorum. Sütun 1 sorunu var, sütun 2 doğru cevabı var ve sütun 3-5 yanlış cevapları var. Her düğümden geçen bir döngü/fonksiyonun nasıl oluşturulacağını ve sadece yanlış cevabı nasıl alacağımı ve her yanlış cevapla birlikte üç sütun oluşturduğundan emin değilim. XML dosyasında:
<answer fraction="100"> doğru bir yanıtı temsil eder ve <answer fraction="0"> yanlış bir yanıtı temsil eder.

cevap

1

Sadece aynı getNodeSet işlevlerini uygularım.

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

Çok teşekkür ederim. Bu gerçekten iyi çalıştı! –