How to create tables in R - r

I am trying to create and export a table for publication (picture attached).
I have created a table using the code below, but I could not export it as a table.
Can anyone help, please
library(tidyverse)
library(gapminder)
data(gapminder)
median_gdp <- median(gapminder$gdpPercap)
gapminder %>%
select(-country) %>%
mutate(gdpPercap = ifelse(gdpPercap > median_gdp, "high", "low")) %>%
mutate(gdpPercap = factor(gdpPercap)) %>%
mutate(pop = pop / 1000000) -> gapminder
gapminder <- lapply(gapminder, function(x) x[sample(c(TRUE, NA),
prob = c(0.9, 0.1),
size = length(x),
replace = TRUE
)])
library(arsenal)
table_one <- tableby(continent ~ ., data = gapminder)
summary(table_one, title = "Gapminder Data", text=TRUE)

If you want to write a table to Microsoft Word, you can use the following code from arsenal package.
write2word(table_one, "table.doc",
keep.md = TRUE,
quiet = TRUE,
title = "Your title")
You can also write a table to pdf and HTML by using the arsenal package. For the details, see
?write2specific

Weirdly, there doesn't seem to be a general question on this topic, though see Create a PDF table for PDFs.
Modern packages to print tables in output formats, including PDF, HTML and Word, include gt, huxtable, flextable and kableExtra.
Packages to create tables of summary statistics include skimr, summarytools and qwraps2. Some of these also have built-in output to different formats.
There are many other packages out there.

Related

webshot2::webshot is trimming the right side off of a huxtable in R

I am trying to convert an html table created in R via the huxtable package to a png file using webshot2::webshot. Unfortunately, the very right side of the output seems to get trimmed off and I can't figure out how to fix this generically.
I don't want to manually tweak the cliprect parameter because I'll need to do this for many tables and its not scalable if its not generic. However, it is possible to achieve it with this parameter so I wonder why its failing with the other workflow.
Here's an example illustrating the problem:
library(magrittr)
library(huxtable)
set.seed(1337)
data <- matrix(rnorm(25), 35, 10)
my_hux <- as_hux(data) %>%
set_outer_borders(0.4) %>%
map_background_color(by_rows("grey95", "white")) %>%
map_text_color(by_quantiles(c(0.1, 0.9), c("red", "black", "green3")))
quick_html(my_hux, file = "ahuxtable.html", open = FALSE)
webshot2::webshot(url = "ahuxtable.html", file = "ahuxtable.png",
zoom = 5, selector = "table")
I tried this with webshot::webshot, however the webshot package seems to be webshot2's predecessor so I'd prefer a webshot2 solution if there is one.

gt table in R Markdown not being outputted

I just discovered the gt library and was excited to try it out but no matter what I did, the tables keep being outputted as a function???
The code is the same on the homepage of the gt website, the gt(x) is literally being processed as a function as we can see from the picture. I updated all my packages and even installed the developer version as well but I keep getting this function output
gt table function output, no table
You can use the gtsave function and save as a .png and it will output. For example, here is a plot that I generated with the following code:
{r mOS Table Generation, fig.dim=c(6,8)}
mostable <- mosdf %>%
ungroup %>%
select(-Dose) %>%
gt() %>%
tab_header(title = "Median Overall Survival (mOS)", subtitle = md("*Subjects Treated from REDACTED*")) %>%
tab_spanner(
label = "95% Confidence Interval",
columns = c(5:6)) %>%
cols_align(align = "center") %>%
tab_style(cell_text(weight = "bold"),
locations = list(cells_title(groups = c("title", "subtitle")),
cells_column_spanners(spanners = everything()),
cells_column_labels(columns = c(1:4)))) %>%
tab_style(cell_text(style = "italic"),
locations = cells_row_groups(groups = everything()))
setwd(output)
gtsave(mostable, "mostable.png", vwidth = 1500, vheight = 1000)
Here is how it looks the R Markdown when knitted to Word:
Note, even though I have the dimension statement in the chunk code, gtsave is dependent on webshot, so the vwidth and vheight control the size of the output to the working directory. Most of the time the output size is fine, but I am still working through how to change the output size. Most of the time I just manually do it, but prefer to not have to update the output. I am going to ask another question, so I will link if there is a solution.
My apologies, turns out there's also a function called "gt" in the expss package I had loaded that interfered with it, looks like I'm not getting my hour back from trying to troubleshoot this lol

Save DiagrammeR object to PNG on disc

I am using the lavaanPlot-Package to plot my Path Model created with lavaan. Works like a charm. Just to make it easier here is a reproducible example
Reproducible Example
library(pacman)
p_unload()
p_load(dplyr,lavaan,webshot,lavaanPlot)
model <- 'mpg ~ cyl + disp + hp
qsec ~ disp + hp + wt'
fit <- sem(model, data = mtcars)
summary(fit)
plot <- lavaanPlot(model = fit,
node_options = list(shape = "box", fontname = "Helvetica"),
edge_options = list(color = "grey"),
coefs = F)
plot
However I would like to save the result to a png file on my disc (rather than utilizing some
form of screenshot). Digging in the docs I found out that lavaanPlot returns a Diagrammer Object.
I tried to get a png file with three different approaches
Approaches
1. Webshot
Gives me the error webshot.js returned failure value: 1
2. export_graph
I found some suggestion how to fix it this link on SO, suggesting to use DiagrammeR export_graph. However this gives me the following error:
Fehler: `export_graph()` REASON:
* The graph object is not valid
3. export_svg
Additionally I found this suggested solution on github, which I couldnt get to work either. It produces a SVG file for me which I cant open properly
# Try 1 using webshot
webshot("Plot_test_webshot.png")
# Try 2 export_graph
plot %>%
export_graph(file_name = "pic.png",
file_type = "png")
export_graph(plot,
file_name = "pic.png",
file_type = "png")
# Try 3 export_svg
plot %>%
export_svg() %>%
charToRaw %>%
rsvg_pdf("./path_to_svg_file.svg")
I was able to find a solution in the Github of the maintainer of the package.
Posting this in the hope that anyone in the future looking for a solution will find this
# Export Function for lavaanPlot Obtained from github
# https://github.com/alishinski/lavaanPlot/blob/export_plots/R/plotExportFunctions.R
save_png <- function(plot, path){
DiagrammeRsvg::export_svg(plot) %>%
charToRaw() %>%
rsvg::rsvg() %>%
png::writePNG(path)
}
Also on Github there is a branch in which this functionality is already included.

R create interactive plot with slider which width could be changed like in Google Finance (sizeable time-window)

R create interactive plot with slider which width could be changed, example below, I'm searching in ggvis R package, but other are also welcome :
Have a look at dygraphs and dyRangeSelector().
The dygraphs package is an R interface to the dygraphs JavaScript
charting library. It provides rich facilities for charting time-series
data in R
For more information and examples, have a look at dygraph's github.io:
install.packages("dygraphs")
library(dygraphs)
lungDeaths <- cbind(mdeaths, fdeaths)
dygraph(lungDeaths) %>%
dySeries("mdeaths", label = "Male") %>%
dySeries("fdeaths", label = "Female") %>%
dyOptions(stackedGraph = TRUE) %>%
dyRangeSelector(height = 20)
Which gives:
Highcharts/Highstock it's another great tool for this kind of plots and there is an awesome API wrapper in R: http://jkunst.com/highcharter/

Object "mydata" not found error in rmd

when I run the following code in R Studio, it works (produce the graph). But, when I knit the document to HTML it gives an error as: object "mydata" not found. How can I fix it?
mydata <- read.csv("impt5.csv")
get("mydata")
xyplot(gdppc ~ human + unemp +inv+indust | class, data = mydata,
auto.key = list(x = .85, y = .035, corner = c(0, 0)),
layout = c(4,1), main = "Per capita gdp by class")
set the working directory to the folder containing your CSV file.
You might want to create a R markdown file instead (.rmd), this is a easy to create an HTML document,or for any other format you want.
Please look into the R markdown help document.
Hope this helps.
More precisely, use:
mydata <- read.csv(paste0(getwd(),"impt5.csv"))
paste0() is the paste() function with sep=" "

Resources