rvest scrape в Rmarkdown не работает, хотя код работает без вязки - PullRequest
2 голосов
/ 07 апреля 2020

Я запускаю код, он отлично работает. Я пытаюсь связать и получаю эту ошибку:

Ошибка: невозможно переименовать столбцы, которые не существуют. Столбец Tests<U+2009>/millionpeople не существует.

Я пытался очистить кеш, загрузить изображение при запуске, создать новый объект для работы по переименованию и изменению, и многое другое. Вероятно, возникает ошибка, потому что очищенный объект не загружается (или не обнаруживается) во время вязания, но я не могу понять, почему или как это исправить.

Есть идеи? Спасибо!

Мой код:

library(utils) library(httr) library(tidyverse) library(rvest) library(ggpubr)

#scrapes from wikipedia, xpath is correct url <- "https://en.wikipedia.org/wiki/COVID-19_testing"  tests <- url %>%     read_html() %>%   html_nodes(xpath='//*[@id="mw-content-text"]/div/table[4]') %>%    html_table() %>%    extract2(1) %>% # extracts data table from html list   rename(country = "Country or region", tests = "Tests", positive
= "Positive", asof = "As of", 
         tests_per_million = "Tests /millionpeople" ,
         positive_per_thousand_tests = "Positive /thousandtests", ref = "Ref.") %>%   mutate(tests = as.numeric(gsub(",", "", tests)), positive = as.numeric(gsub(",", "", positive)),
         tests_per_million = as.numeric(gsub(",", "", tests_per_million)),
         positive_per_thousand_tests = round(positive_per_thousand_tests, 0)) #removes commas and coverts to numeric'

1 Ответ

0 голосов
/ 07 апреля 2020

В таблице есть несколько разных имен со специальными символами, которые могут вызывать проблему. Поскольку вы хотите переименовать все столбцы, используйте rename_all.

library(rvest)
library(dplyr)
library(readr)

url <- "https://en.wikipedia.org/wiki/COVID-19_testing"

tests <-  url %>%     
  read_html() %>%
  html_nodes(xpath='//*[@id="mw-content-text"]/div/table[4]') %>%
  html_table() %>%
  .[[1]] %>%
  rename_all(~c("country", "tests", "positive", "asof", 
                "tests_per_million","positive_per_thousand_tests", "ref")) %>%   
   mutate(tests = parse_number(tests), positive = parse_number(positive),
          tests_per_million = parse_number(tests_per_million),
          positive_per_thousand_tests = round(positive_per_thousand_tests)) 
...