2017-09-18 57 views
0

我正在尝试将一个xml文件导入到R中。它的格式如下,每行上有一个事件,后面跟着一些属性 - 哪些取决于事件类型。这个文件是0.7GB,未来的版本可能会更大。我想创建一个数据框,每个事件都在一个新行上,并且所有可能的属性都在不同的列中(意思是根据事件类型不同而不同)。我在其他地方寻找答案,但他们似乎都在处理树形结构中的XML文件,我无法弄清楚如何将它们应用于这种格式。将XML导入R数据框

我是R新手,对XML文件没有经验,所以请给我一些“傻瓜”的答案,并附上大量的解释。谢谢!

<?xml version="1.0" encoding="utf-8"?> 
<events version="1.0"> 
    <event time="21510.0" type="actend" person="3" link="1" actType="h" /> 
    <event time="21510.0" type="departure" person="3" link="1" legMode="car" /> 
    <event time="21510.0" type="PersonEntersVehicle" person="3" vehicle="3" /> 
    <event time="21510.0" type="vehicle enters traffic" person="3" link="1" vehicle="3" networkMode="car" relativePosition="1.0" /> 

... 

</events> 

回答

1

你可以尝试这样的事情:

original_xml <- '<?xml version="1.0" encoding="utf-8"?> 
    <events version="1.0"> 
     <event time="21510.0" type="actend" person="3" link="1" actType="h" /> 
      <event time="21510.0" type="departure" person="3" link="1" legMode="car" /> 
       <event time="21510.0" type="PersonEntersVehicle" person="3" vehicle="3" /> 
        <event time="21510.0" type="vehicle enters traffic" person="3" link="1" vehicle="3" networkMode="car" relativePosition="1.0" /> 
        </events>' 
library(xml2) 

data2 <- xml_children(read_xml(original_xml)) 
attr_names <- unique(names(unlist(xml_attrs(data2)))) 

xmlDataFrame <- as.data.frame(sapply(attr_names, function (attr) { 
    xml_attr(data2, attr = attr) 
}), stringsAsFactors = FALSE) 

#-- since all columns are strings, you may want to turn the numeric columns to numeric 

xmlDataFrame[, c("time", "person", "link", "vehicle")] <- sapply(xmlDataFrame[, c("time", "person", "link", "vehicle")], as.numeric) 

如果你有额外的“数字”列,可以在最后将它们添加到数据转换到正确的类。