【问题标题】:How would I parse the XML file in R and carry out basic Statistics Analysis on the data我将如何解析 R 中的 XML 文件并对数据进行基本的统计分析
【发布时间】:2010-07-10 04:01:00
【问题描述】:

我正在尝试在 R 中解析 XML 文件,以便分析数据。我正在尝试获取价格的均值和标准差。此外,我希望能够获得股价变化时的变化率。我曾尝试手动输入数据,但日期结构有问题(我尝试了以下方法:

z <- strptime ("HH:MM:SS.ms, "%H:%m:%S.%f")

但它失败了)。我知道 XML 文件只有少量数字,但它是一个可以自动化的过程吗?如果可以,我需要什么包? (我是 R 新手)。任何帮助将不胜感激。

谢谢, 安东尼。

<?xml version = "1.0"?>
    <Company >
    <shareprice>
    <timeStamp> 12:00:00:01</timeStamp>
    <Price>  25.02</Price>
    </shareprice>



    <shareprice>
    <timeStamp> 12:00:00:02</timeStamp>
    <Price>  15</Price>
    </shareprice>



    <shareprice>
    <timeStamp> 12:00:00:025</timeStamp>
    <Price>  15.02</Price>
    </shareprice>



    <shareprice>
    <timeStamp> 12:00:00:031</timeStamp>
    <Price>  18.25</Price>
    </shareprice>



    <shareprice>
    <timeStamp> 12:00:00:039</timeStamp>
    <Price>  18.54</Price>
    </shareprice>



    <shareprice>
    <timeStamp> 12:00:00:050</timeStamp>
    <Price> 16.52</Price>
    </shareprice>


   <shareprice>
    <timeStamp> 12:00:01:01</timeStamp>
    <Price>  17.50</Price>
   </shareprice>
</Company>

【问题讨论】:

    标签: xml r


    【解决方案1】:

    z <- strptime ("HH:MM:SS.ms, "%H:%m:%S.%f")
    

    你错过了一个结束 " 所以它是无效的语法。

    接下来,数据是非标准的,因为我们将使用点表示 seconds.subseconds,即 12:23:34.567 来表示时间戳。毫秒可以这样解析

    > ts <- "12:00:00.050"
    > strptime(ts, "%H:%M:%OS")
    [1] "2010-07-09 12:00:00 CDT"
    > 
    

    所以你不仅需要先把它从XML中取出来,还需要对字符串进行转换。否则,您可以解析字符串并“手动”填充POSIXlt 时间结构。

    Postscriptum:忘了说你需要启用亚秒级打印:

    > options("digits.secs"=3)         # shows milliseconds (three digits)
    > strptime(ts, "%H:%M:%OS")
    [1] "2010-07-09 12:00:00.05 CDT"   # suppresses trailing zero
    > 
    

    Postscriptum 2:感谢XML 包,您的文件也很幸运:

    > library(XML)
    > xmlToDataFrame("c:/Temp/foo.xml")     # save your data as c:/Temp/foo.xml
          timeStamp   Price
    1   12:00:00:01   25.02
    2   12:00:00:02      15
    3  12:00:00:025   15.02
    4  12:00:00:031   18.25
    5  12:00:00:039   18.54
    6  12:00:00:050   16.52
    7   12:00:01:01   17.50
    > 
    

    【讨论】:

    • 嗨,Dirk,感谢您的快速回复。我按照您提供的步骤并添加了以下内容: library (XML) test.df
    • 也许可以试试 mean(as.numeric(Price))。
    【解决方案2】:

    对于更复杂的 XML 数据,使用 XML 包可能有用。

    library(XML)
    
    check <- xmlInternalTreeParse("/PathToXMLFile/checkXML.xml")
    xpathSApply(check, "//timeStamp", xmlValue)
    ## [1] " 12:00:00:01"  " 12:00:00:02"  " 12:00:00:025" " 12:00:00:031"
    ## [5] " 12:00:00:039" " 12:00:00:050" " 12:00:01:01" 
    

    【讨论】:

    • 我上次的更新也是通过更容易使用的xmlToDataFrame()函数使用XML
    猜你喜欢
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多