【发布时间】:2019-08-27 02:53:51
【问题描述】:
我正在使用 Shiny 和 R 以交互方式可视化我的数据。我想在 Iris 数据集中绘制 Petal.Width 与 Petal.Length 的交互式散点图,并根据 k 个集群(用户输入)和 p(专用于训练数据集(用户输入)的数据行的百分比)对点进行聚类。我在散点图中添加了悬停功能,以便通过单击每个点,将展示该点的整个数据集。
# Loading Libraries
library(shiny)
library(caret)
library(ggplot2)
data(iris)
ui <- pageWithSidebar(
headerPanel("Clustering iris Data"),
sidebarPanel(
sliderInput("k", "Number of clusters:",
min = 1, max = 5, value = 3),
sliderInput("prob", "Training percentage:",
min=0.5, max=0.9, value = 0.7)),
mainPanel(
# img(src='iris_types.jpg', align = "center", height="50%", width="50%"),
plotOutput("plot1", click = "plot_click"),
verbatimTextOutput("info")
)
)
server <- function(input, output) {
inTrain <- createDataPartition(y=iris$Species,
p=input$prob,
list=FALSE)
training <- iris[ inTrain,]
testing <- iris[-inTrain,]
kMeans1 <- kmeans(subset(training,
select=-c(Species)),
centers=input$k)
training$clusters <- as.factor(kMeans1$cluster)
output$plot1 <- renderPlot({
qplot(Petal.Width,
Petal.Length,
colour = clusters,
data = training,
xlab="Petal Width",
ylab="Petal Length")
})
output$info <- renderPrint({
# With ggplot2, no need to tell it what the x and y variables are.
# threshold: set max distance, in pixels
# maxpoints: maximum number of rows to return
# addDist: add column with distance, in pixels
nearPoints(iris, input$plot_click, threshold = 10, maxpoints = 1,
addDist = FALSE)
})
}
shinyApp(ui, server)
当我在 R Studio 中运行应用程序时,我收到以下错误:
Error in .getReactiveEnvironment()$currentContext() :
Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
【问题讨论】:
-
input$prob是一个反应值。您必须将数据包装在响应式内容中。例如reactiveValues() -
@Clemsang 谢谢。你能再解释一下吗?哪一行需要改?
-
inTrain、training、testing是动态的。您可以为observe中的每个人创建reactiveValues。这样,您可以在输入更改时修改 3 个对象。当您可以使用数据时,您还必须在服务器中使用reactiveValues$object_name更改对这三个对象的调用。仔细看reactiveValues()
标签: r shiny shiny-server shiny-reactivity