2016-05-27 73 views
0

我有兩個XML文件,我想解析成R 中的數據框,然後進行合併。將數據框列表到正常的數據框

獲取XML文件轉換成數據幀上市

library(XML) 
library(plyr) 

getxmldf<-function(xmlfile){ 

    booksz <- xmlTreeParse(xmlfile) 
    xmldf<-ldply(xmlToList(booksz), data.frame) 
    xmldf.T <- t(xmldf[,2:ncol(xmldf)]) 
    return(xmldf.T) 

} 

然後選擇不公開其&做了合併,但我被困在不公開&合併不起作用......

df8 <- as.data.frame(lapply(df8, function(X) unname(unlist(X)))) 
merge(df8, df8, by = c("V5")) 
str(df8, max.level = 1) 

我附上兩個測試XML文件。他們是地址轉儲從「作弊引擎」

https://drive.google.com/file/d/0BxCrQYKS04mRV1ZEZ1Bza2Vabkk/view?usp=sharing

https://drive.google.com/file/d/0BxCrQYKS04mRRWJUVjdqRUp3Yk0/view?usp=sharing

回答

0

我已經採取了看看你的文件,它們似乎並不有很多在他們感興趣的信息。

在每個文件中都有許多CheatEntry節點,每個節點包含5個節點:ID,Description,LastState,VariableType和Address。

ID始終按順序排列,第一個文件從0到87,第二個文件從0到110。

說明總是''沒有說明''。

LastState始終爲空。它具有兩個屬性:第一個文件中始終爲6042,第二個文件中爲6122的值,以及始終與Address節點相同的RealAddress。所以這兩個屬性都沒有提供任何真實的信息。

VariableType總是「4字節」。

地址有一個8位十六進制字符串,它在兩個文件內部和之間總是唯一的。


鑑於上述所有,我不確定爲什麼要合併它們。在R中,「合併」通常意味着在一個密鑰上加入行,但是我們從這兩個文件中獲得的數據集之間沒有共同的密鑰。實際上,ID可能是有道理的,但鑑於你似乎在你的問題中嘗試了「V5」,這看起來並不正確。

我假設你想結合兩個data.frames排,這可以用rbind()函數來完成。我們可以使用lapply()一次性處理這兩個文件,然後使用do.call()調用單個文件data.frames上的rbind()調用。

此外,我建議避免xmlToList()有利於有針對性地搜索與xpathApply() CheatEntry節點,然後調用助手xmlToDataFrame()函數。這也將允許我們使用xmlToDataFrame()colClassesstringsAsFactors參數來控制結果列的數據類型。

把所有的這一起,我們有:

xmlFiles <- list.files(pattern='\\.CT$'); 
xmlFiles; 
## [1] "CivilizationBE_DX11-6042.TXT.CT" "CivilizationBE_DX11-6122.TXT.CT" 
res <- do.call(rbind,lapply(xmlFiles,function(xmlFile) 
    xmlToDataFrame(
     xpathApply(xmlInternalTreeParse(xmlFile),'//CheatEntry'), 
     c('integer','character','character','character','character'), 
     stringsAsFactors=F 
    ) 
)); 
head(res); tail(res); 
## ID  Description LastState VariableType Address 
## 1 0 "No description"    4 Bytes 0AEEE67C 
## 2 1 "No description"    4 Bytes 0AEEE68C 
## 3 2 "No description"    4 Bytes 0AF6E67C 
## 4 3 "No description"    4 Bytes 0AF6E68C 
## 5 4 "No description"    4 Bytes 0B827378 
## 6 5 "No description"    4 Bytes 0B8992C8 
##  ID  Description LastState VariableType Address 
## 194 105 "No description"    4 Bytes 25E7EAC4 
## 195 106 "No description"    4 Bytes 25E7EAC8 
## 196 107 "No description"    4 Bytes 25E7EAD4 
## 197 108 "No description"    4 Bytes 2E15F970 
## 198 109 "No description"    4 Bytes FF6A673C 
## 199 110 "No description"    4 Bytes FFBCA308