Errors in publishing rPresentation slidedeck - r

Have published in rPubs the following codes of rPresentation.
Some of the charts are not displaying properly. Just wondering what I am missing ?Guidance in this regard will be helpful.
Thanks
Link of presentation : http://rpubs.com/shan/Presentation3
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)
```

Related

How to take userinput in flexdashboard shiny as number of cluster to run kmeans in r?

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

dynamic tabsets with multiple plots r markdown

I managed to create a html document that creates dynamic tabsets based on a list of items. Adding one plot works fine on one tabset. How can I add now multiple plots on one tabset?
Hereby the code I started from but it only shows 1 plot per tabset when you knit the document to html output. obviously there is still something missing.
---
title: "R Notebook"
output:
html_document:
df_print: paged
editor_options:
chunk_output_type: inline
---
### header 1
```{r}
library(ggplot2)
df <- mtcars
pl_list <- list()
pl1 <- qplot(cyl, disp, data = df[1:12,])
pl2 <- qplot(mpg, cyl, data = df[13:20,])
pl3 <- qplot(mpg, cyl, data = df[21:30,])
pl4 <- qplot(mpg, cyl, data = df[1:12,])
pl_list[[1]] <- list(pl1, pl3, "one")
pl_list[[2]] <- list(pl2, pl4, "two")
```
### header {.tabset}
```{r, results = 'asis', echo = FALSE}
for (i in seq_along(pl_list)){
tmp <- pl_list[[i]]
cat("####", tmp[[3]], " \n")
print(tmp[1])
cat(" \n\n")
}
```
There are a couple of improvements you can do.
Create cat header function with arguments for text and level.
With it you don't need to call cat multiple times and it creates wanted number of # automatically.
catHeader <- function(text = "", level = 3) {
cat(paste0("\n\n",
paste(rep("#", level), collapse = ""),
" ", text, "\n"))
}
print plots using lapply.
Full code looks like this:
---
title: "R Notebook"
output:
html_document:
df_print: paged
editor_options:
chunk_output_type: inline
---
```{r, functions}
catHeader <- function(text = "", level = 3) {
cat(paste0("\n\n",
paste(rep("#", level), collapse = ""),
" ", text, "\n"))
}
```
### header 1
```{r}
library(ggplot2)
df <- mtcars
pl_list <- list()
pl1 <- qplot(cyl, disp, data = df[1:12,])
pl2 <- qplot(mpg, cyl, data = df[13:20,])
pl3 <- qplot(mpg, cyl, data = df[21:30,])
pl4 <- qplot(mpg, cyl, data = df[1:12,])
pl_list[[1]] <- list(pl1, pl3, "one")
pl_list[[2]] <- list(pl2, pl4, "two")
```
## header {.tabset}
```{r, results = "asis", echo = FALSE}
for(i in seq_along(pl_list)){
tmp <- pl_list[[i]]
# As you want to use tabset level here has to be lower than
# parent level (ie, parent is 2, so here you have to use 3)
catHeader(tmp[[3]], 3)
lapply(tmp[1:2], print)
}
```

R Markdown not displaying plotly graphics

I am using Rstudio Version 1.1.447. on a Dell Latitude E5470 using Windows 10. I am trying to create a presentation for an assignment using R markdown and knittr and ioslides. The resultant presentation has a complete black page instead of the graph. The graph however does display in Rstudio if I run the code on its own outside of R markdown.
Here is my code:
```{r, echo = TRUE, include=FALSE}
library("plotly")
library("ggplot2")
library("datasets")
data("state")
x <- state.area
y <- state.x77[,1]*1000
z <- state.x77[,5]
fac <- state.division
newdf <- as.data.frame(cbind(state.area, state.x77[,1]*1000, state.x77[,5], state.division))
colnames(newdf) <- c("Area", "Population", "Murder", "Division")
p <-plot_ly(newdf,
x="Area",
y="Population",
z="Murder",
type="scatter3d",
mode="markers",
color="Division")
p
```
Try the same but removing the {r, echo = TRUE, include=FALSE} and replace it with just {r}.
Here is a complete working answer.
---
title: "Plotly in Markdown Example"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library("plotly")
library("ggplot2")
library("datasets")
data("state")
x <- state.area
y <- state.x77[,1]*1000
z <- state.x77[,5]
fac <- state.division
```
## Plot title goes here
Awesome comments about plot output goes here:
```{r}
newdf <- as.data.frame(cbind(state.area, state.x77[,1]*1000, state.x77[,5], state.division))
colnames(newdf) <- c("Area", "Population", "Murder", "Division")
p <-plot_ly(newdf,
x="Area",
y="Population",
z="Murder",
type="scatter3d",
mode="markers",
color="Division")
p
```

Loops in Rmarkdown: How to make an in-text figure reference? Figure captions?

{r setup, include=FALSE, message=FALSE, results="hide"}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(kfigr)
library(dplyr)
library(png)
library(grid)
library(pander)
library(ggplot2)
Question
Loops in rmarkdown: in-text figure reference? figure captions?
Goal
Use a for loop to create sections with text, in-text results, and multiple figure references with associated figure captions in the figure list. The figure references/numbering should be seemless with figures numbered before and after these new sections.
Note: The figures referenced in the for loop are generated earlier in the text, saved as pngs, and then re-loaded. This might seem clunky for the purpose of this example, but the actual figs are maps and are slow to generate (I plan to comment out the loop that generates the figures once I have them how I want).
{r echo = FALSE, warnings=FALSE, message=FALSE, results="hide"}
Data: Each year we have a different number of strata, hence the need for a loop.
df <- rbind(
data.frame(strata = rep("A", 10), x = rnorm(10, mean= 10), y = rnorm(10, mean = 15),z = rnorm(10, mean = 20)),
data.frame(strata = rep("B", 10), x = rnorm(10, mean= 5), y = rnorm(10, mean = 10), z = rnorm(10, mean = 15)),
data.frame(strata = rep("C", 10), x = rnorm(10, mean= 15), y = rnorm(10, mean = 20), z = rnorm(10, mean = 10)))
first_plot: the figure that should appear in the list before for loop creates the sections by strata
first_plot <- ggplot(df, aes(x, fill=strata)) + geom_histogram()
last_plot: the figure that should appear in the list after the for loop creates the sections by strata
last_plot <- ggplot(df, aes(x = strata, y = z)) + geom_boxplot()
Figure generation (this is the part that will be commented out later in my version once I have the maps how I want)
strat <- unique(df$strata)
for (i in seq_along(strat)) {
sub <- df %>% filter(strata %in% strat[i])
fig1 <- ggplot(sub, aes(x = x, y = y)) + geom_point()
ggsave(fig1, file=paste0("fig1_", strat[i], ".png"))
fig2 <- ggplot(sub, aes(x = x, y = z)) + geom_point()
ggsave(fig2, file=paste0("fig2_", strat[i], ".png"))
}
Load the png's
df_figs <- list.files(pattern = "\\.png$")
for (i in df_figs){
name <- gsub("-",".",i)
name <- gsub(".png","",name)
i <- paste(".\\",i,sep="")
assign(name,readPNG(i))
}
Introduction section
Some introductory text in the report and a figure r figr('first_plot',TRUE, type='Figure').
```{r echo = FALSE, warnings=FALSE, message=FALSE, results = "asis"}
# Summary of results and image file names that will be references in text
results <- df %>%
group_by(strata) %>%
dplyr::summarise_each(funs(mean)) %>%
mutate(fig1 = paste0("fig1_", strata),
fig2 = paste0("fig2_", strata))
#Text template (each strata will have its own section)
template <- "# The %s stratum
The mean of *x* in %s stratum was %1.1f. Relationships between *x* and *y* and *x* and *z* can be found in `r figr('%s', TRUE, type='Figure')` and `r figr('%s', TRUE, type='Figure')`.
"
#Create markdown sections in for loop
for(i in seq(nrow(results))) {
current <- results[i, ]
cat(sprintf(template,
current$strata, current$strata,
current$x,
current$fig1, current$fig2))
}
#Also doesn't work:
template <- "# The %s stratum
The mean in %s stratum was %1.0f. Results can be found in "
template2 <- " and "
template3 <- ".
"
`figr('%s', TRUE, type='Figure')` and `figr('%s', TRUE, type='Figure')`."
#For loop
for(i in seq(nrow(results))) {
current <- results[i, ]
cat(sprintf(template,
current$strata, current$strata,
current$mean,
current$fig_1, current$fig_2))
print(paste0("`r figr(",paste0("'", current$fig1,"'"), TRUE, type='Figure'))
cat(sprintf(template2))
print(paste0("`r figr(",paste0("'", current$fig2,"'"), "TRUE, type='Figure'),`"))
cat(sprintf(template3))
}
```
Conclusion section
Some discussion text in the report and figure r figr('last_plot',TRUE, type='Figure').
Figures
*NOTE:* I don't know how to automate the looped portion of the list of figures here, so I've done it by hand.
```{r 'first_plot', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6, fig.cap="The caption for the first figure."}
suppressMessages(print(first_plot))
```
```{r 'fig1_A', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6, fig.cap="Caption text for fig1_A."}
grid.raster(fig1_A)
```
```{r 'fig2_A', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6, fig.cap="Caption text for fig2_A."}
grid.raster(fig2_A)
```
```{r 'fig1_B', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6, fig.cap="Caption text for fig1_B."}
grid.raster(fig1_B)
```
```{r 'fig2_B', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6, fig.cap="Caption text for fig2_B."}
grid.raster(fig2_B)
```
```{r 'fig1_C', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6, fig.cap="Caption text for fig1_C."}
grid.raster(fig1_C)
```
```{r 'fig2_C', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6, fig.cap="Caption text for fig2_C."}
grid.raster(fig2_C)
```
```{r 'last_plot', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6, fig.cap="The caption for the last figure."}
suppressMessages(print(last_plot))
```
SOLUTIONS
Use knit_expand()
Use captioner instead of kfigr
This numbers your figures (or tables) in text and at the end of your report.
This script shows you how to create markdown paragraphs in for loops that have in-text references to figures.
It also shows you how to create custom figure captions in for loops while retaining the number order.
If you show how to do #4 and #5 using brew I will give you all the SO points.
Libraries
library(knitr)
library(dplyr)
library(png)
library(grid)
library(pander)
library(ggplot2)
library(devtools)
library(captioner)
Create a fig_nums() function using the captioner package
(https://github.com/adletaw/captioner/blob/master/vignettes/using_captioner.Rmd)
fig_nums <- captioner(prefix = "Figure")
Data
Each year we have a different number of strata, hence the need for a loop.
df <- rbind(
data.frame(strata = rep("A", 10), x = rnorm(10, mean= 10), y = rnorm(10, mean = 15), z = rnorm(10, mean = 20)),
data.frame(strata = rep("B", 10), x = rnorm(10, mean= 5), y = rnorm(10, mean = 10), z = rnorm(10, mean = 15)),
data.frame(strata = rep("C", 10), x = rnorm(10, mean= 15), y = rnorm(10, mean = 20), z = rnorm(10, mean = 10)))
first_plot: the figure that should appear in the list before for loop creates the sections by strata
first_plot <- ggplot(df, aes(x, fill=strata)) + geom_histogram()
fig_nums("first_plot", display = FALSE)
last_plot: the figure that should appear in the list after the for loop creates the sections by strata
last_plot <- ggplot(df, aes(x = strata, y = z)) + geom_boxplot()
Figure generation
Comment this section out once you have figs how you want. This step will not feel convoluted, unnatural, suboptimal, unnecessary, or like a very bad idea if you do a lot of mapping in R.
strat <- unique(df$strata)
for (i in seq_along(strat)) {
sub <- df %>% filter(strata %in% strat[i])
fig1 <- ggplot(sub, aes(x = x, y = y)) + geom_point()
ggsave(fig1, file=paste0("fig1_", strat[i], ".png"))
fig2 <- ggplot(sub, aes(x = x, y = z)) + geom_point()
ggsave(fig2, file=paste0("fig2_", strat[i], ".png"))
}
Load the png's
df_figs <- list.files(pattern = "\\.png$")
for (i in df_figs){
name <- gsub("-",".",i)
name <- gsub(".png","",name)
i <- paste(".\\",i,sep="")
assign(name,readPNG(i))
}
Introduction
Some introductory text in the report and a figure r fig_nums("first_plot", display="cite").
Results and image file names that will be referenced in text:
```{r echo = FALSE, warnings=FALSE, message=FALSE, results = "asis"}
results <- df %>%
group_by(strata) %>%
dplyr::summarise_each(funs(mean)) %>%
mutate(fig1 = paste0("fig1_", strata),
fig2 = paste0("fig2_", strata))
```
```{r run-numeric-md, warning=FALSE, include=FALSE}
#The text for the markdown sections in for loop... the knit_expand() is the work-horse here.
out = NULL
for (i in as.character(unique(results$strata))) {
out = c(out, knit_expand(text=c('#### The *{{i}}* strata',
'\n',
'The mean of *x* is ',
'{{paste(sprintf("%1.1f", results$x[results$strata==i]))}}', '({{fig_nums(results$fig1[results$strata==i],display="cite")}}).',
'\n'
)))
}
```
Creates section for each strata
`r paste(knit(text = out), collapse = '\n')`
Conclusion
Some discussion text in the report and figure r fig_nums("last_plot",display="cite").
List of Figures
`r fig_nums("first_plot",caption="Here is the caption for the first figure.")`
```{r 'first_plot', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6}
suppressMessages(print(first_plot))
```
```{r figcaps, include=FALSE}
caps = NULL
for (i in as.character(unique(results$strata))) {
caps = c(caps, knit_expand(
text=c({{fig_nums(results$fig1[results$strata==i], caption="Caption text for strata *{{i}}* goes here.")}},
'``` {r {{results$fig1[results$strata==i]}}, echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6}',
{{paste0('grid.raster(',results$fig1[results$strata==i],')')}},
'```',
'\n')))
}
#DON'T FORGET TO UNLIST!
src <- unlist(caps)
```
`r paste(knit(text = src),sep='\n')`
`r fig_nums("last_plot", caption="The caption for the last figure.")`
```{r 'last_plot', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6}
suppressMessages(print(last_plot))
```

rCharts and gvisMotionChart are not displayed when published in rPubs

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

Resources