2

You can easily print out an rpart tree result in text in R console with the following command.

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

And it prints out:

n= 81

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

1) root 81 17 absent (0.79012346 0.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) *

However, this does not work in Rshiny textOutput.
See the following Rshiny Code:

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

If I run the above shiny APP, it give the following error:

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

4

1 回答 1

2

You can use capture.output(fit) to get the string outputted by the print function. You might also want to change the textOutput in the ui.R to an htmlOutput. This allows you to have a multiline text output.

Code would be like this: 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")
        )
)
)
于 2015-02-05T18:29:26.733 回答