私は国連ウェブサイトのWFPからRでウェブを吟味し、食糧安全保障に関するアップデート(http://www.fao.org/countryprofiles/en/)を含むデータセットを構築しています。 パッケージは、rvest、stringr、tidyr、data.table、plyr、xml2、jsonliteです。 しかし、データセットの国名、記事のURL、記事のタイトル、記事のテキストをインポートしました。 解析を簡単にするため、興味のあるキーワード(例:「食料安全保障」、「干ばつ」など)を含む新しい変数を設定し、前述のキーワードの通貨を記録します。 その変数は私の研究を非常に単純化します。 提案がありますか?Rウェブスクレイピング設定キーワード
ここでは私が使用している基本コードを示します。
## 01. Creating a function in order to scrape data from a website (in this case, FAO's)
WFP_get_news <- function(countries) { GET(
url = "http://www1.wfp.org/countries/common/allnews/en/",
query = list(countries=countries)
) -> res
warn_for_status(res)
if (status_code(res) > 399) return(NULL)
out <- content(res, as="text", encoding="UTF-8")
out <- jsonlite::fromJSON(out)
out$countries <- countries
tbl_df(out)
}
## 02. Setting all the Country urls in order for them to be automatically scraped
pb <- progress_estimated(length(countrycode_data$countries[]))
map_df(countrycode_data$countries[], ~{
pb$tick()$print()
Sys.sleep(5)
wfp_get_news(.x)
}) -> xdf
## 03. Setting keywords (of course, this process is arbitrary: one can decide any keywor s/he prefers)
keywords <- c("drought", "food security")
keyword_regex <- sprintf("(%s)", paste0(keywords, collapse="|"))
## 04. Setting the keywords search
bind_cols(
xdf,
stri_match_all_regex(tolower(xdf$bodytext), keyword_regex) %>%
map(~.x[,2]) %>%
map_df(~{
res <- table(.x, useNA="always")
nm <- names(res)
nm <- ifelse(is.na(nm), "NONE", stri_replace_all_regex(nm, "[ -]", "_"))
as.list(set_names(as.numeric(res), nm))
})
) %>%
select(-NONE) -> xdf_with_keyword_counts
私はポイント04から取得した結果は
Error in overscope_eval_next(overscope, expr) :
object "NONE" not found
Furthermore: Warning message:
Unknown or uninitialised column: 'data.frame'.
任意の手がかりとなりますか?
あなたはポストこするデータ '言及したキーワードに基づいてデータをフィルタリングすることができ、私たちにあなたが –
より良い – Ileeo
上向きのコードを示すのを助けるためにしようとしているコードを表示してくださいgrep() 'などが役立つはずです。そのアプローチに問題はありますか? – abhiieor