Lecture 9: twitteR

R package: memoise

キャッシュに保存

Twitterアプリケーションの作成&登録

OAuth 認証用

https://apps.twitter.com/

ROAuth, twitteRのインストール

install.packages("twitteR")
install.packages("ROAuth")

ROAuth, twitteRのインストールの読み込み

library(twitteR)
library(ROAuth)

twitteRからのOauth認証

cacert.pemをダウンロード

download.file(url = "http://curl.haxx.se/ca/cacert.pem", destfile = "cacert.pem")

認証情報(Twitterアプリケーション)

consr_key = "***********"
consr_secrt = "***********"
req_url = "https://api.twitter.com/oauth/request_token"
acs_url = "https://api.twitter.com/oauth/access_token"
auth_url = "https://api.twitter.com/oauth/authorize"
cred <- OAuthFactory$new(consumerKey = consr_key, consumerSecret = consr_secrt, 
    requestURL = req_url, accessURL = acs_url, authURL = auth_url)

handshake: twitterクライアント接続

cred$handshake(cainfo = "cacert.pem")

alt text

OAuth認証の登録

registerTwitterOAuth(cred)

検索例

searchTwitter("#olympics", n = 10)
userTimeline(username)

shinyでtwitteR利用

shinyで実装

shinyのロード

library(shiny)

shiny作業フォルダの作成:wcould

ui.Rの作成

shinyUI(bootstrapPage(

  # Application title
  headerPanel("twitteR"),

  # Sidebar
  sidebarPanel(
    textInput("keyword", 
              "検索キーワード:",
              value="#olympics"),
      uiOutput("controlColor"),

      sliderInput(inputId = "num",
            label = "The maximum number of tweets to return: ",
            min = 5, max = 50, value=5),
      HTML("<hr>"),
      p("wordcould用オプション"),
      sliderInput(inputId = "s1",
                label = "Scale size 1: ",
                min = 4, max = 10, value=4),
      sliderInput(inputId = "s2",
                  label = "Scale size 2: ",
                  min = 0.5, max = 1.0, value=0.5, step=0.1),
      HTML("<hr>"),
      uiOutput("wordIndexControls")
    ),

  mainPanel(

    tabsetPanel(    
      tabPanel("検索結果", tableOutput("search")),
      tabPanel("wordcloud", plotOutput("wordCloud")),
      tabPanel("棒グラフ", plotOutput("barplot"))
    )

  )
))

server.R (枠組み)

shinyServer(function(input, output) {

  output$search <- renderTable({

  })

  output$wordCloud <- renderPlot({

  })

  output$barplot <- renderPlot({

  })

  output$controlColor <- renderUI({

  })

  output$wordIndexControls <- renderUI({

  })


})

global.R

library(memoise)
getFreq <- memoise(function(txt, relative = FALSE) {

    wordLst <- strsplit(txt, "[[:space:]]|[[:punct:]]")
    wordLst <- unlist(wordLst)
    wordLst <- tolower(wordLst)
    wordLst <- wordLst[wordLst != ""]

    freq <- sort(table(wordLst), decreasing = TRUE)
    if (relative == TRUE) {
        freq <- round(freq/sum(freq), 3)
    }
    freqMtx <- data.frame(freq)
    return(freqMtx)
})

output$search

output$search <- renderTable({
    res <- searchTwitter(input$keyword, n = input$num)
    res <- sapply(res, function(x) x$getText())
    cbind(res)
})

output$wordCloud

output$wordCloud <- renderPlot({
    col <- brewer.pal(11, input$palet)
    res <- searchTwitter(input$keyword, n = input$num)
    res <- sapply(res, function(x) x$getText())
    freqL <- getFreq(res)
    wordcloud(rownames(freqL), freqL$freq, colors = col, scale = c(input$s1, 
        input$s2))
})

output$barplot

output$barplot <- renderPlot({
    col <- brewer.pal(11, input$palet)
    res <- searchTwitter(input$keyword, n = input$num)
    res <- sapply(res, function(x) x$getText())
    freqL <- getFreq(res)

    title = "Word Frequency Distribution"
    ylabel = "Frequency"
    min <- input$range[1]
    max <- input$range[2]
    barplot(freqL$freq[min:max], las = 2, main = title, ylab = ylabel, col = col)
})

output$controlColor

output$controlColor <- renderUI({
    binfo <- brewer.pal.info[]
    palets <- rownames(binfo[binfo$maxcolors > 9, ])

    selectInput(inputId = "palet", label = "Choose a palet", choices = palets, 
        selected = palets[1])
})

output$wordIndexControls

output$wordIndexControls <- renderUI({

    res <- searchTwitter(input$keyword, n = input$num)
    res <- sapply(res, function(x) x$getText())
    freqL <- getFreq(res)
    wmax <- length(freqL$freq)
    sliderInput("range", "Word index Range (棒グラフ):", min = 1, max = wmax, 
        value = c(1, wmax), step = 1)
})

twitteRアプリケーションの起動

runApp("twitteR")