2015-02-05 39 views
2

可以使用以下命令輕鬆在R控制檯中打印rpart樹結果文本。如何在Rshiny中打印出rpart樹結果文本

fit <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis) 
print(fit) 

而且它打印出:

n= 81

node), split, n, loss, yval, (yprob) * denotes terminal node

1) root 81 17 absent (0.79.20987654) 2) Start>=8.5 62 6 absent (0.90322581 0.09677419)
4) Start>=14.5 29 0 absent (1.00000000 0.00000000) * 5) Start< 14.5 33 6 absent (0.81818182 0.18181818)
10) Age< 55 12 0 absent (1.00000000 0.00000000) * 11) Age>=55 21 6 absent (0.71428571 0.28571429)
22) Age>=111 14 2 absent (0.85714286 0.14285714) * 23) Age< 111 7 3 present (0.42857143 0.57142857) * 3) Start< 8.5 19 8 present (0.42105263 0.57894737) *

然而,這並不在Rshiny textOutput工作。
請參閱以下Rshiny代碼:

ui.r

library(shiny) 

# Define UI for application that draws a histogram 
shinyUI(fluidPage(

    # Application title 
    # Show a plot of the generated distribution 
    mainPanel(
     plotOutput("distPlot"), 
     textOutput("distText") 
    ) 
) 
) 

server.r

library(shiny) 
library(rpart) 
# Define server logic required to draw a histogram 
shinyServer(function(input, output) { 
    output$distText <- renderText({ 
    fit <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis) 
    print(fit) 
    }) 
}) 

如果我運行上面閃亮的應用程序,它提供以下錯誤:

Error in cat(list(...), file, sep, fill, labels, append) :
argument 1 (type 'list') cannot be handled by 'cat'

回答

2

您可以使用capture.output(fit)獲取輸出的字符串b y打印功能。 您可能還需要將ui.R中的textOutput更改爲htmlOutput。這允許你有一個多行文本輸出。

代碼將是這樣的: server.R

library(shiny) 
library(rpart) 
# Define server logic required to draw a histogram 
shinyServer(function(input, output) { 

     output$distText <- renderText({ 
       fit <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis) 
       paste(capture.output(fit),collapse="<br>") 


     }) 
}) 

ui.R

library(shiny) 

# Define UI for application that draws a histogram 
shinyUI(fluidPage(

     # Application title 
     # Show a plot of the generated distribution 
     mainPanel(
       plotOutput("distPlot"), 
       htmlOutput("distText") 
     ) 
) 
)