Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
---
title: "OJS and Shiny Reactives"
format:
html:
code-tools:
source: https://github.com/quarto-dev/quarto-web/blob/main/docs/interactive/ojs/examples/_shiny/kmeans/kmeans-shiny-ojs.qmd
server:
type: shiny
---
[K-Means Clustering](https://shiny.rstudio.com/gallery/kmeans-example.html) example
from the Shiny Gallery implemented with an OJS client and Shiny Server.
The source code for client and server are shown below. Alternatively,
click **Code** and **View Source** above to see the source in full.
```{ojs}
//| panel: sidebar
vars = ["Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"]
viewof xcol = Inputs.select(vars, {label: "X Variable", value: vars[0]})
viewof ycol = Inputs.select(vars, {label: "Y Variable", value: vars[1]})
viewof count = Inputs.range([1, 9], {label: "Cluster Count", step: 1, value: 3})
```
```{ojs}
//| panel: fill
Plot.plot({
color: {
type: "ordinal",
scheme: "category10"
},
marks: [
Plot.dot(transpose(selectedData), {
x: xcol,
y: ycol,
fill: (d, i) => clusters.cluster[i],
}),
Plot.dot(clusters.centers, {
x: d => d[0],
y: d => d[1],
r: 10,
stroke: "black",
fill: (d, i) => i + 1
}),
]
})
```
```{r}
#| context: server-start
library(readr)
library(ggplot2)
library(dplyr)
```
```{r}
#| context: server
selectedData <- reactive({
req(input$xcol)
req(input$ycol)
iris[, c(input$xcol, input$ycol)]
})
clusters <- reactive({
req(input$count)
kmeans(selectedData(), input$count)
})
ojs_define(selectedData, clusters)
```
::: {.panel-tabset}
### OJS Client
```{{ojs}}
//| panel: sidebar
vars = ["Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"]
viewof xcol = Inputs.select(vars, {label: "X Variable", value: vars[0]})
viewof ycol = Inputs.select(vars, {label: "Y Variable", value: vars[1]})
viewof count = Inputs.range([1, 9], {label: "Cluster Count", step: 1, value: 3})
```
```{{ojs}}
//| panel: fill
Plot.plot({
color: {
type: "ordinal",
scheme: "category10"
},
marks: [
Plot.dot(transpose(selectedData), {
x: xcol,
y: ycol,
fill: (d, i) => clusters.cluster[i],
}),
Plot.dot(clusters.centers, {
x: d => d[0],
y: d => d[1],
r: 10,
stroke: "black",
fill: (d, i) => i + 1
}),
]
})
```
### Shiny Server
```{{r}}
#| context: server-start
library(readr)
library(ggplot2)
library(dplyr)
```
```{{r}}
#| context: server
selectedData <- reactive({
req(input$xcol)
req(input$ycol)
iris[, c(input$xcol, input$ycol)]
})
clusters <- reactive({
req(input$count)
kmeans(selectedData(), input$count)
})
ojs_define(selectedData, clusters)
```
:::