iT邦幫忙

0

[R語言]資料視覺化W01─wordcloud

Hi! 大家好久不見!我是Eric。相信最近大家都只想待在家裡吧,怕一出門就被武漢肺炎感染!!!
那這次我們就要利用wordcloud來看看關於武漢肺炎新聞中最常用到的是什麼字呢?
/images/emoticon/emoticon04.gif


緣起:最近武漢肺炎肆虐全球,甚至死亡人數超越了當年的SARS,世界衛生組織WHO就趕到中國瞭解情況。
方法:運用[R語言]的[wordcloud]套件。
使用資料:WHO team arrives in China as Wuhan coronavirus deaths top SARS,
By James Griffiths, CNN;Updated 0439 GMT (1239 HKT) February 11, 2020。https://edition.cnn.com/2020/02/10/asia/wuhan-coronavirus-update-intl-hnk/index.html


1. 載入套件。

install.packages("tm")          # text mining,文字探勘套件,可將文字檔轉檔給R處理
install.packages("wordcloud")   # 本次主角,產出文字雲
library(tm)
library(wordcloud)

2. 載入資料與初步查看。

dirPath <- "~/Desktop/R/"    # 設定檔案路徑
WuHan <- Corpus(DirSource(dirPath)) # 將路徑中的資料載入

inspect(WuHan)  # 檢視檔案的結構

https://ithelp.ithome.com.tw/upload/images/20200211/20115774BAo1zRPvES.png

3. 資料清理。

WuHan <- tm_map(WuHan, content_transformer(tolower))     # 將文字全部轉成小寫
WuHan <- tm_map(WuHan, removeNumbers)                    # 移除數字(因我們只想看文字)
WuHan <- tm_map(WuHan, removeWords,stopwords("english")) # 將stopwords(常用的較無意義的字)刪除,如this、a、we等
WuHan <- tm_map(WuHan, removePunctuation)                # 刪除標點符號
WuHan <- tm_map(WuHan, stripWhitespace)                  # 刪除空白

dtm <- TermDocumentMatrix(WuHan)                         # 用來傳送文字資料
m <- as.matrix(dtm)                                      # 轉成矩陣
v <- sort(rowSums(m), decreasing = TRUE)                 # 依據單字出現的頻率由高排到低
d <- data.frame(word = names(v), freq=v)                 # 製造文字與頻率的資料框
head(d, 10)                                              # 查看結果

https://ithelp.ithome.com.tw/upload/images/20200211/20115774l8EcGFutJC.png

4. 大功告成。

wordcloud(words = d$word, freq = d$freq, colors = brewer.pal(8, "Dark2"), random.order = FALSE)  # 用wordcloud創造文字雲,另可增加min.word=數字及max.word=數字兩個參數,分別設定要顯示多少頻率的文字

https://ithelp.ithome.com.tw/upload/images/20200211/20115774pUGytW7zxK.png

可以看出最常出現的單字依序為health、china、virus、said,等等...said這個較無意義的字跑了進來,看來只使用stopwords參數無法完全解決,因此,我們要再次篩選資料。

5. 重新啟動。

WuHan <- tm_map(WuHan, removeWords,c("said"))  # 將想要篩掉的文字加到參數
wordcloud(words = d$word, freq = d$freq, colors = brewer.pal(8, "Dark2"), random.order = FALSE)   # 重新產出文字雲

https://ithelp.ithome.com.tw/upload/images/20200211/20115774iXMWkG53GX.png

可以看到said不見了!!所以我們之後就可以運用R語言的wordcloud套件,針對想查看的文章進行探勘,挖出文章潛在想表達的意思。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言