我目前正在研究預測模型,為此我想將 HTML 網站中的資料匯入 R 并將資料集的值部分保存到新串列中。
我在 R 中使用了以下方法:
# getting website data:
link <- "https://www.tradegate.de/orderbuch.php?isin=US13200M5085"
document <- htmlParse(GET(link, user_agent("Mozilla")))
removeNodes(getNodeSet(document,"//*/comment()"))
doc.tables<-readHTMLTable(document)
# show BID/ASK block:
doc.tables[2]
doc.tables[2]在這種情況下,哪個 ( ) 給了我結果:
$`NULL`
Bid 0,765
1 Ask 0,80
如何過濾掉表格的數字(0,765 和 0,80),將其保存到串列中?
uj5u.com熱心網友回復:
問題是 0.765 實際上是您的 data.frame 列的名稱。
您的資料框是 doc.tables[[2]]
您可以通過呼叫 names(doc.tables[[2]])[2]) 來獲取名稱
將其存盤為變數,例如 name <- names(doc.tables[[2]])[2])
然后您可以使用 doc.tables[[2]][[2]] 獲取 0,80,如果您愿意,可以將其存盤為變數。
最終代碼應如下所示... my_list <- list(name, doc.tables[[2]][[2]])
uj5u.com熱心網友回復:
這里有一種方式 with rvest,而不是 package XML。
下面的代碼使用另外兩個包stringr和readr, 來提取值及其名稱。
library(httr)
library(rvest)
library(dplyr)
link <- "https://www.tradegate.de/orderbuch.php?isin=US13200M5085"
page <- read_html(link)
tbl <- page %>%
html_elements("tr") %>%
html_text() %>%
.[3:4] %>%
stringr::str_replace_all(",", ".")
tibble(name = stringr::str_extract(tbl, "Ask|Bid"),
value = readr::parse_number(tbl))
#> # A tibble: 2 x 2
#> name value
#> <chr> <dbl>
#> 1 Bid 0.765
#> 2 Ask 0.8
由reprex 包于 2022-03-26 創建(v2.0.1)
在不將管道結果保存到臨時物件的情況下,tbl管道可以繼續如下。
library(httr)
library(rvest)
library(stringr)
suppressPackageStartupMessages(library(dplyr))
link <- "https://www.tradegate.de/orderbuch.php?isin=US13200M5085"
page <- read_html(link)
page %>%
html_elements("tr") %>%
html_text() %>%
.[3:4] %>%
str_replace_all(",", ".") %>%
tibble(name = str_extract(., "Ask|Bid"),
value = readr::parse_number(.)) %>%
.[-1]
#> # A tibble: 2 x 2
#> name value
#> <chr> <dbl>
#> 1 Bid 0.765
#> 2 Ask 0.8
由reprex 包于 2022-03-27 創建(v2.0.1)
uj5u.com熱心網友回復:
這是基于 Jahi Zamy 的觀察,即您的一些資料顯示為列名以及問題中的示例代碼。
library(httr)
library(XML)
# getting website data:
link <- "https://www.tradegate.de/orderbuch.php?isin=US13200M5085"
document <- htmlParse(GET(link, user_agent("Mozilla")))
# readHTMLTable() assumes tables have a header row by default,
# but these tables do not, so use header=FALSE
doc.tables <- readHTMLTable(document, header=FALSE)
# Extract column from BID/ASK table
BidAsk = doc.tables1[[2]][,2]
# Replace commas with point decimal separator
BidAsk = as.numeric(gsub(",", ".", BidAsk))
# Convert to numeric
BidAsk = as.numeric(BidAsk)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/450204.html
上一篇:使用列名展開所有列
下一篇:通過R中最接近的值合并兩個資料幀
