我如何解析R中的XML文件并对数据进行基本的统计分析

Ant*_*ane 4 xml r

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

z <- strptime ("HH:MM:SS.ms, "%H:%m:%S.%f")
Run Code Online (Sandbox Code Playgroud)

但它无法工作).我知道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>
Run Code Online (Sandbox Code Playgroud)

Dir*_*tel 8

z <- strptime ("HH:MM:SS.ms, "%H:%m:%S.%f")
Run Code Online (Sandbox Code Playgroud)

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

接下来,数据是非标准的,因为我们将使用dot.subseconds,即12:23:34.567来表示时间戳.毫秒可以通过这种方式解析

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

因此,您不仅需要首先从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
> 
Run Code Online (Sandbox Code Playgroud)

后记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
> 
Run Code Online (Sandbox Code Playgroud)