从 R 中的网站提取数据并将其显示为 R 表
Pulling in data from websites in R and diplaying them as R tables
我正在尝试用 shiny 构建一个财务仪表板,但卡在了第一步。我想写一篇文章,内容如下table
from https://stockanalysis.com/stocks/
并在我闪亮的环境中将其显示为 table。类似于我下面的内容,但是 table 应该显示来自任一链接的内容,而不是随机正态分布。
library(shiny)
ui <- fluidPage(
sliderInput(inputId = "num",
label = "Choose a number",
value = 25, min = 1, max = 100),
dataTableOutput("T")
)
server <- function(input, output) {
output$T <- renderDataTable({
data.frame(x=rnorm(input$num))
})
}
shinyApp(ui = ui, server = server)
您需要使用 R 中的 rvest
库来抓取 table。
您可以使用安装包
install.packages("rvest")
.
要抓取 table,您需要检查网页并找出 table ID。它看起来像这样:
代码如下所示:
library(rvest)
library(dplyr)
url <- ("https://stockanalysis.com/stocks/")
page <- read_html(url)
stocks <- page %>%
html_nodes('table#symbol-table') %>%
html_table() %>% .[[1]]
整个 Shiny App 将如下所示:
library(shiny)
library(rvest)
library(dplyr)
url <- ("https://stockanalysis.com/stocks/")
page <- read_html(url)
page
stocks <- page %>%
html_nodes('table#symbol-table') %>%
html_table() %>% .[[1]]
ui <- fluidPage(
sliderInput(inputId = "num",
label = "Choose a number",
value = 25, min = 1, max = 100),
dataTableOutput("T")
)
server <- function(input, output) {
output$T <- renderDataTable({
stocks
})
}
shinyApp(ui = ui, server = server)
我正在尝试用 shiny 构建一个财务仪表板,但卡在了第一步。我想写一篇文章,内容如下table
并在我闪亮的环境中将其显示为 table。类似于我下面的内容,但是 table 应该显示来自任一链接的内容,而不是随机正态分布。
library(shiny)
ui <- fluidPage(
sliderInput(inputId = "num",
label = "Choose a number",
value = 25, min = 1, max = 100),
dataTableOutput("T")
)
server <- function(input, output) {
output$T <- renderDataTable({
data.frame(x=rnorm(input$num))
})
}
shinyApp(ui = ui, server = server)
您需要使用 R 中的 rvest
库来抓取 table。
您可以使用安装包
install.packages("rvest")
.
要抓取 table,您需要检查网页并找出 table ID。它看起来像这样:
代码如下所示:
library(rvest)
library(dplyr)
url <- ("https://stockanalysis.com/stocks/")
page <- read_html(url)
stocks <- page %>%
html_nodes('table#symbol-table') %>%
html_table() %>% .[[1]]
整个 Shiny App 将如下所示:
library(shiny)
library(rvest)
library(dplyr)
url <- ("https://stockanalysis.com/stocks/")
page <- read_html(url)
page
stocks <- page %>%
html_nodes('table#symbol-table') %>%
html_table() %>% .[[1]]
ui <- fluidPage(
sliderInput(inputId = "num",
label = "Choose a number",
value = 25, min = 1, max = 100),
dataTableOutput("T")
)
server <- function(input, output) {
output$T <- renderDataTable({
stocks
})
}
shinyApp(ui = ui, server = server)