I am trying to replicate the functionality of an Excel pivot table using a Flexdashboard with crosstalk and DT. I need to be able to show both a data table and a summary table, and be able to apply the same filters on both tables at the same time.
The example below works to filter using one field, "manufacturer". What I can't seem to figure out is how to add another filter, like say "continent", to work on both tables.
---
title: "Filter 2 tables With Crosstalk"
output:
flexdashboard::flex_dashboard:
orientation: rows
vertical_layout: scroll
theme: cosmo
---
```{r setup, include=FALSE}
library(dplyr)
library(crosstalk)
car_data <- "manufacturer,model,displ,year,cyl,trans,drv,cty,hwy,fl,class,continent
audi,a4,1.8,1999,4,auto,f,18,29,p,compact,europe
audi,a4,1.8,1999,4,manual,f,21,29,p,compact,europe
audi,a4,2,2008,4,manual,f,20,31,p,compact,europe
audi,a4,2,2008,4,auto,f,21,30,p,compact,europe
audi,a4,2.8,1999,6,auto,f,16,26,p,compact,europe
chevrolet,malibu,2.4,1999,4,auto,f,19,27,r,midsize,america
chevrolet,malibu,2.4,2008,4,auto,f,22,30,r,midsize,america
chevrolet,malibu,3.1,1999,6,auto,f,18,26,r,midsize,america
chevrolet,malibu,3.5,2008,6,auto,f,18,29,r,midsize,america
chevrolet,malibu,3.6,2008,6,auto,f,17,26,r,midsize,america
dodge,caravan 2wd,2.4,1999,4,auto,f,18,24,r,minivan,america
dodge,caravan 2wd,3,1999,6,auto,f,17,24,r,minivan,america
dodge,caravan 2wd,3.3,1999,6,auto,f,16,22,r,minivan,america
dodge,caravan 2wd,3.3,1999,6,auto,f,16,22,r,minivan,america
dodge,caravan 2wd,3.3,2008,6,auto,f,17,24,r,minivan,america"
# Create df1 & df2
mpg_cars <- read.csv(header = TRUE, text = car_data)
summary_mpg <- mpg_cars %>%
group_by(continent,
manufacturer) %>%
summarize(cty = mean(cty),
hwy = mean(hwy),
models = n())
```
Row
------------------------
### Filters
```{r include=TRUE, message=FALSE}
############### This Works! #######################
sd1 <- SharedData$new(mpg_cars,
~manufacturer,
group = "Manufacturer")
sd2 <- SharedData$new(summary_mpg,
~manufacturer,
group = "Manufacturer")
#
filter_select("manufacturer",
"Manufacturer:",
sd1,
~manufacturer)
```
### Shared Summary
```{r include=TRUE, message=FALSE}
DT::datatable(sd2)
```
Row
-----------------------------------------------------------------------
### Shared data
```{r include=TRUE, message=FALSE}
DT::datatable(sd1)
```
I have tried the following, but it did not work right.
############## Do multiple fields work? #####################
# sd1 <- SharedData$new(mpg_cars, group = "individual")
# sd2 <- SharedData$new(summary_mpg, group = "individual")
#
# filter_select(id = "group1",
# sharedData = sd1,
# group = ~manufacturer,
# label = "Mfg. Filter")
#
# filter_select(id = "group2",
# sharedData = sd1,
# group = ~continent,
# label = "Cont. Filter")
I am new to shiny/flexdashboard and so far have been able to render plots and filter dataframe by using values from selectInput with help of req(input$user_input_value) .
ISSUE: To run kmeans I am taking user input for number of clusters which I am not able to code it in reactive format and getting error: object of type closure is not subsettable.
```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(tidyverse)
library(tidytext)
library(scales)
library(glue)
library(widyr)
library(factoextra)
```
df
1 2 3 4
Angola -0.08260540 0.034325891 -0.02013353 -0.014063951
Armenia -0.06613693 -0.044308626 -0.13230387 -0.024534033
Azerbaijan -0.07562365 -0.003670707 0.05886792 -0.219660410
Bahrain -0.08275891 0.035843793 -0.02280102 -0.008044934
Bangladesh -0.08306371 0.032998297 -0.02634819 -0.017627316
Bosnia & Herzegovina -0.06303898 -0.050781511 -0.15183954 0.016794674
(Note: I have placed the csv file in github & mentioned its link below. For kmeans the character column should be used as rownames which represents country here.)
UPDATED df CREATION STEP
svd_dimen_all_wide <- read.csv(url("https://raw.githubusercontent.com/johnsnow09/covid19-df_stack-code/main/svd_dimen_all_wide.csv"))
svd_dimen_all_wide <- as.data.frame(svd_dimen_all_wide)
rownames(svd_dimen_all_wide) <- svd_dimen_all_wide$X
svd_dimen_all_wide <- svd_dimen_all_wide[,2:ncol(svd_dimen_all_wide)]
flexdashboard
---
title: "UN Country Votes"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
theme: space
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(tidyverse)
library(tidytext)
library(scales)
library(glue)
library(widyr)
library(factoextra)
Page NAme
=====================================
Inputs {.sidebar}
-----------------------------------------------------------------------
```{r}
selectInput("number_of_clusters", label = h3("Number of Clusters"),
choices = c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15) ,
selected = 6)
```
Column {data-width=1000}
-----------------------------------------------------------------------
```{r include=FALSE}
set.seed(123)
km.res <- reactive({
# req(input$number_of_clusters)
kmeans(svd_dimen_all_wide, as.numeric(input$number_of_clusters), nstart = 25)
})
df_with_cluster <- cbind(svd_dimen_all_wide, cluster = km.res$cluster)
df_with_cluster <- rownames_to_column(df_with_cluster, "country")
df_with_cluster <- df_with_cluster %>%
select(country, cluster, everything())
```
UPDATED ATTEMPT:
renderPrint({
df_with_cluster <- cbind(svd_dimen_all_wide, cluster = km.res()$cluster)
df_with_cluster <- rownames_to_column(df_with_cluster, "country")
df_with_cluster <- df_with_cluster %>%
select(country, cluster, everything())
head(df_with_cluster)
})
### Comparison of Countries on Yes% of Bi Words
```{r}
renderPlot({
world_data %>%
left_join((df_with_cluster %>%
mutate(country_code = countrycode(country, "country.name", "iso2c"))
),
by = c("country_code")) %>%
filter(!is.na(cluster)) %>%
ggplot(aes(x = long, y = lat, group = group,
fill = as.factor(cluster))) +
geom_polygon() +
theme_map() +
scale_fill_discrete() +
labs(fill = "cluster",
title = "World Clusters based on UN voting",
caption = "created by ViSa") +
theme(plot.title = element_text(face = "bold", size = 16))
})
```
The problem is in a reactive chunk. The reactive expression km.res uses an input number of clusters, runs a model, and saves the output. (and let's end the code chunk here).
Next, decide what do you want to do with the output?
to print the result, use renderPrint
to show as a plot, use renderPlot,
to show as a table, user renderTable, etc.
Now Let's print the output of the model with renderPrint() the output can be accessed by calling the expression’s name followed by parenthesis, e.g., km.res()
Column {data-width=1000}
-----------------------------------------------------------------------
```{r include=FALSE}
km.res <- reactive({
req(input$number_of_clusters)
set.seed(123)
kmeans(svd_dimen_all_wide, as.numeric(input$number_of_clusters), nstart = 25)
})
```
###
```{r model}
renderPrint({
df_with_cluster <- cbind(svd_dimen_all_wide, cluster = km.res()$cluster)
head(df_with_cluster)
})
```
Here is my blog post very relevant to this problem https://towardsdatascience.com/build-an-interactive-machine-learning-model-with-shiny-and-flexdashboard-6d76f59a37f9?sk=922526470699966c3f47b24843404a15
I'm trying to create a dynamic number of tabs in my rmd with some content inside.
This one doesn't help.
Something like this:
---
title: "1"
output: html_document
---
```{r }
library(highcharter)
library(tidyverse)
iris %>%
dplyr::group_split(Species) %>%
purrr::map(.,~{
# create tabset for each group
..1 %>%
hchart("scatter", hcaes(x = Sepal.Length, y = Sepal.Width))
})
```
You can set results = 'asis' knitr option to generate the tabs in the map function using cat.
Getting Highcharter to work with asis was trickier :
Highchart needs to be called once before the asis chunck, probably to initialize properly, hence the first empty chart.
to print the chart in the asis chunck, the HTML output is sent in character format to cat
Try this:
---
title: "Test tabs"
output: html_document
---
`r knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, cache = F)`
```{r}
library(highcharter)
library(tidyverse)
# This empty chart is necessary to initialize Highcharter in the tabs
highchart(height = 1)
```
```{r, results = 'asis'}
cat('## Tabs panel {.tabset} \n')
invisible(
iris %>%
dplyr::group_split(Species) %>%
purrr::imap(.,~{
# create tabset for each group
cat('### Tab',.y,' \n')
cat('\n')
p <- hchart(.x,"scatter", hcaes(x = Sepal.Length, y = Sepal.Width))
cat(as.character(htmltools::tagList(p)))
})
)
```
Note that while this solution works well, it goes beyond the original use for asis
I have made a rpresenter file. The code is displayed below. When I published in rPubs, slides with words are displayed. But the motion charts and other charts are not displayed, showing:
AccessDeniedAccess Denied573371FF628EBE0CmrHb5GPTc+1Ul1K15psqFpJ/f6dovc+frwQougDVtROA6ZQajWyye0Jr9CvH
I had gone through the RStudio documentation. I was wondering how to display the charts properly. Thanks in anticipation.
Presentation On Datasets
========================================================
author: Harry
date: 8/27/2016
autosize: true
Selecting The Data
========================================================
### We will select the diamonds dataset available in package 'ggplot2'.
Lets look at the data.
```{r}
library(ggplot2)
head(diamonds)
```
Summary Of Data
========================================================
### Lets view the summary of data
```{r}
library(ggplot2)
summary(diamonds)
```
Charts
========================================================
### Lets display some charts.
```{r results = 'asis', comment = NA}
library(rCharts)
library(ggplot2)
n1 <- nPlot(carat ~ cut , group = "color", data = diamonds[1:40,], type = "multiBarChart")
n1
```
Plot
=============================================================
### Plotting Chart from economics dataset
```{r results = 'asis', comment = NA}
library(rCharts)
data(economics, package = 'ggplot2')
econ <- transform(economics, date = as.character(date))
m1 <- mPlot(x = 'date', y = c('psavert', 'uempmed'), type = 'Line',data = econ)
m1$set(pointSize = 0, lineWidth = 1)
m1
```
Plot
============================================================
### Lets plot some Geographical Data
```{r gvisMergeExample, results='asis', echo=FALSE}
library(googleVis)
Geo <- gvisGeoChart(Exports, locationvar='Country', colorvar='Profit',
options=list(height=300, width=350))
Tbl <- gvisTable(Exports, options=list(height=300, width=200))
plot(gvisMerge(Geo, Tbl, horizontal=TRUE))
```
Plot
=========================================
### Lets plot Fruit vs Year
```{r MotionChartExample, results='asis', tidy=FALSE}
library(googleVis)
M <- gvisMotionChart(Fruits, 'Fruit', 'Year', options=list(width=400, height=350))
plot(M)
```