2017-12-18 134 views
0

有關此數據提取的問題我做了。我想創建一個帶有數據的條形圖,但不幸的是,我無法將提取的字符轉換爲R中的數字。如果我在文本編輯器中編輯該文件,根本沒有porblem,但是我想要做的全部在R.過程這是代碼:R:將字符轉換爲R data.frame中的數字

install.packages("rvest") 
    library(rvest) 

    url <- "https://en.wikipedia.org/wiki/Corporate_tax" 

    corporatetax <- url %>% 
    read_html() %>% 
    html_nodes(xpath='//*[@id="mw-content-text"]/div/table[5]') %>% 
    html_table() 

    str(corporatetax) 

corporatetax結果是,有3個變量所有這些字符的data.frame。我還沒有解決的問題是,我應該如何將第二和第三列轉換爲數字來創建條形圖?我嘗試過使用sapply()和dplyr(),但沒有找到正確的方法來做到這一點。

謝謝!

+2

您是否嘗試過as.numeric並將其應用到每個要轉換的列?例如df $ column_1 < - as.numeric(df $ column_1) –

+0

您可能需要刪除非數字字符,比如「%」,我通常使用'gsub()'作爲此 – Nate

+0

和現在的「corporatetax」是一個列表,而不是一個data.frame。用'corporatetax [[1]]'提取data.frame – Nate

回答

0

您可以嘗試清理桌子這樣

library(rvest) 
library(stringr) 
library(dplyr) 

url <- "https://en.wikipedia.org/wiki/Corporate_tax" 

corporatetax <- url %>% 
    read_html() %>% 
    # your xpath defines the single table, so you can use html_node() instead of html_nodes() 
    html_node(xpath='//*[@id="mw-content-text"]/div/table[5]') %>% 
    html_table() %>% as_tibble() %>% 
    setNames(c("country", "corporate_tax", "combined_tax")) 

corporatetax %>% 
    mutate(corporate_tax=as.numeric(str_replace(corporate_tax, "%", ""))/100, 
     combined_tax=as.numeric(str_replace(combined_tax, "%", ""))/100 
     )