Lecture 10: shinyでtwitteR利用

前回の補足

server.R (output$wordCloud)

output$wordCloud

output$wordCloud <- renderPlot({

    name <- input$univName
    # print(paste('univ',name, sep='$')) ex. univ$hiroshima
    freq <- eval(parse(text = paste("univ", name, sep = "$")))
    # freq<-univ[,colnames(univ)==input$univName]と同じ結果

    col <- brewer.pal(11, input$palet)
    wordcloud(rownames(univ), freq, colors = col, scale = c(input$s1, input$s2))
})

eval関数

目的:ファイル名の文字列(ex.hiroshima)を変数として使用するため

univ$hiroshima
eval(parse(text = paste("univ", name, sep = "$")))

twitteRからのOAuth認証

ROAuth, twitteRパッケージの読み込み

library(twitteR)
library(ROAuth)

認証情報(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")

OAuth認証の登録

registerTwitterOAuth(cred)

検索例

res <- searchTwitter("#olympics", n = 10)

検索結果のテキスト抽出

res <- sapply(res, function(x) x$getText())

getFreqMtxDir.Rの読み込み

source("getFreqMtxDir.R")

単語頻度表の作成

freqL <- getFreq(res)

wordcloudのロード

library(wordcloud)

## wordcloudで描画

wordcloud(rownames(freqL), freqL$freq, min.freq = 2)

## 棒グラフ描画

title = "Word Frequency Distribution"
xlabel = "Word"
ylabel = "Frequency"
barplot(freqL$freq[1:20], las = 2, main = title, xlab = xlabel, ylab = ylabel)

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({

  })


})

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)
})

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

runApp("twitteR")