Setting area in RMarkdown - r

I am trying to make dashboard with flexidasboard in RMarkdown. I try to adapt this code below
Page 2
=======================================================================
Row
-----------------------------------------------------------------------
```{r global1, include=FALSE}
# load data in 'global' chunk so it can be shared by all users of the dashboard
library(biclust)
data(BicatYeast)
set.seed(1)
res <- biclust(BicatYeast, method=BCPlaid(), verbose=FALSE)
```
Inputs {.sidebar}
-----------------------------------------------------------------------
```{r}
selectInput("clusterNum", label = h3("Cluster number"),
choices = list(" I01" = 1,
" I02" = 2,
" I03" = 3,
"4" = 4, "5" = 5),
selected = 1)
```
Microarray data matrix for 80 experiments with Saccharomyces Cerevisiae
organism extracted from R's `biclust` package.
Sebastian Kaiser, Rodrigo Santamaria, Tatsiana Khamiakova, Martin Sill, Roberto
Theron, Luis Quintales, Friedrich Leisch and Ewoud De Troyer. (2015). biclust:
BiCluster Algorithms. R package version 1.2.0.
http://CRAN.R-project.org/package=biclust
Row
-----------------------------------------------------------------------
### Heatmap
```{r}
num <- reactive(as.integer(input$clusterNum))
col = colorRampPalette(c("red", "white", "darkblue"), space="Lab")(10)
renderPlot({
p = par(mai=c(0,0,0,0))
heatmapBC(BicatYeast, res, number=num(), xlab="", ylab="",
order=TRUE, useRaster=TRUE, col=col)
par(p)
})
```
Row {.tabset}
-----------------------------------------------------------------------
### Parallel Coordinates
```{r}
renderPlot(
parallelCoordinates(BicatYeast, res, number=num())
)
```
### Data for Selected Cluster
```{r}
# only display table for values in cluster 4
renderTable(
BicatYeast[which(res#RowxNumber[, num()]), which(res#NumberxCol[num(), ])]
)
```
And input from this code look like pic below. I am not satisfied with the look especially because I like to use grey area which is marked with yellow circle or in other word I like to increase Heatmap and use this part.
So can anybody help me how I can use this grey area?

Just remove the first:
Row
-----------------------------------------------------------------------
under the Page2 title. This adds an empty line before the .sidebar column.

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

rmarkdown resize plot inside of code chunk

I have an rmarkdownfile with a chunck that has a loop that creates many pages. Below is a toy example. See the "loop_chunk" code chunk. The "loop_chunk" has fig.width=9, fig.height=6, results="asis" and I am running into a problem where i need to reduce the size of a plot inside loop_chunk. All plots are 9x6 but I need to adjust one plot. I found the codee below: http://michaeljw.com/blog/post/subchunkify/
and I tried using it below but when you run the code you can see that there are 2 plots on pages 3 and 5 and there should not be. it is somehow not keeping the \newpages. There should be 1 plot on pages 2,3,4 and 5. There should only be 5 pages.
Any idea how to fix this?
---
title: "Untitled"
output: pdf_document
toc: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE , comment = NA, message= FALSE, warning = TRUE)
subchunkify <- function(g, fig_height=7, fig_width=5) {
g_deparsed <- paste0(deparse(
function() {g}
), collapse = '')
sub_chunk <- paste0("
`","``{r sub_chunk_", floor(runif(1) * 10000), ", fig.height=", fig_height, ", fig.width=", fig_width, ", echo=FALSE}",
"\n(",
g_deparsed
, ")()",
"\n`","``
")
cat(knitr::knit(text = knitr::knit_expand(text = sub_chunk), quiet = TRUE))
}
data = data.frame(group= c("A","A"), value = c(1,3))
```
```{r loop_chunk, fig.width=9, fig.height=6, results="asis", message= FALSE, warning = FALSE}
for(i in 1:nrow(data)){
cat(paste0("\\newpage\n # Page ", i ," \n"))
plot(data$value[i])
cat("\n\n")
cat(paste0("\\newpage\n ## page with smaller plot \n\n"))
cat("Here is some text on this page for the smaller plot.")
cat("\n\n")
data2 = data.frame(x = 7, y = 900)
library(ggplot2)
myplot = ggplot(data2, aes(x = x, y = y ))+geom_point()
subchunkify(myplot , 4,4 )
# print(myplot) -> IS there a way to just reduce the height and width with print()?
cat("\n\n")
}
```
Using your subchunkify() function for the graphics::plot call outputs those plots to the intended pages. Replacing plot(data$value[i]) in your second chunk with
subchunkify(plot(data$value[i]), 5, 5)
outputs the 5 pages with plots as intended (where height & width are set to 5/can be edited to conditionally set dimensions for a specific plot).

Errors in publishing rPresentation slidedeck

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

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