2015-09-22 200 views
0

我运行下面的代码在R:创建一个数据帧R

library(xml2) 

doc <- read_html('http://www.southcarolinagasprices.com/GasPriceSearch.aspx?typ=adv&fuel=A&srch=0&area=All%20Areas&station=All%20Stations&tme_limit=4') 

prices <- xml_find_all(doc, xpath="//div[@class='sp_p']") 

sapply(prices, function(x) { 
as.numeric(paste(gsub("d", "\\.", 
        gsub("^p", "", 
         unlist(xml_attrs(xml_find_all(x, "./div"))))), 
       collapse="")) 
}) 

## [1] 1.65 1.65 1.65 1.65 1.65 1.65 1.65 1.65 1.65 1.67 1.68 1.69 1.69 1.69 1.69 1.69 1.69 1.69 1.69 
## [20] 1.70 1.71 1.72 1.72 1.73 1.73 1.73 1.73 1.73 1.73 1.73 1.73 1.73 1.74 1.74 1.74 1.74 1.74 1.74 
## [39] 1.74 1.74 1.74 1.75 1.75 1.75 1.75 1.75 1.75 1.75 1.75 1.75 1.75 1.75 1.75 1.75 1.75 1.76 1.76 
## [58] 1.76 1.76 1.76 1.76 1.76 1.76 1.76 1.76 1.76 1.76 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 
## [77] 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 
## [96] 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.77 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 
## [115] 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 
## [134] 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.78 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 
## [153] 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 
## [172] 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 
## [191] 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 1.79 

我怎么能这个值转换为一个data.frame?我需要导出此值以导出为.csv或.txt

+0

维度是否有任何约束? –

回答

1
library(xml2) 

    doc <- read_html('http://www.southcarolinagasprices.com/GasPriceSearch.aspx? typ=adv&fuel=A&srch=0&area=All%20Areas&station=All%20Stations&tme_limit=4') 

    prices <- xml_find_all(doc, xpath="//div[@class='sp_p']") 

    test<-sapply(prices, function(x) { 
    as.numeric(paste(gsub("d", "\\.", 
         gsub("^p", "", 
          unlist(xml_attrs(xml_find_all(x, "./div"))))), 
        collapse="")) 
    }) 
df_test<-data.frame(test) 
write.csv(df_test, file=df_test.csv)