2017-12-18 21 views
0

このデータ抽出に関する質問をしました。私はデータを使って棒グラフを作成したいのですが残念ながらR内の数字に抽出された文字を変換することはできません。テキストエディタでファイルを編集すると、まったく問題はありませんが、 R.の処理は、ここでは、コードです:R:Rデータフレーム内の文字を数値に変換する

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があります。私が解決しようとしていなかった私の質問は、2番目と3番目の列を数字に変換して棒グラフを作成する方法です。私はsapply()とdplyr()で試しましたが、正しい方法を見つけられませんでした。

ありがとうございます!

+2

あなたはas.numericみました。このようなテーブルをクリーンアップして、変換したい列のそれぞれに適用しようとするのでしょうか?例えばdf $ column_1 < - as.numeric(df $ column_1) –

+0

"%"のような数字以外の文字を削除する必要があるかもしれませんが、通常は – Nate

+0

に 'gsub()'を使用し、現在は 'corporatetax'リストであり、data.frameではありません。 data.frameを 'corporatetax [[1]]'で抽出する – 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 
     ) 
関連する問題