Wrap Rmarkdown md_output table chunk output in code chunks - r

I want my Rmarkdown, when converted to .md, text chunk output to be wrapped in code ticks (``` * ```).
For example as it is now, an Rmarkdown document like so:
---
title: 'This is a test title'
date: '`r Sys.Date()`'
output:
md_document:
variant: commonmark #or gfm
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
message = FALSE,
warning = FALSE
)
```
```{r echo=FALSE}
library(palmerpenguins)
```
```{r echo=TRUE}
penguins
```
This is some text.
Rendered with rmarkdown::render("path/to/test.Rmd") to:
```
penguins
```
## # A tibble: 344 × 8
## species island bill_le…¹ bill_…² flipp…³ body_…⁴ sex year
## <fct> <fct> <dbl> <dbl> <int> <int> <fct> <int>
## 1 Adelie Torgersen 39.1 18.7 181 3750 male 2007
## 2 Adelie Torgersen 39.5 17.4 186 3800 fema… 2007
## 3 Adelie Torgersen 40.3 18 195 3250 fema… 2007
## 4 Adelie Torgersen NA NA NA NA <NA> 2007
## 5 Adelie Torgersen 36.7 19.3 193 3450 fema… 2007
## 6 Adelie Torgersen 39.3 20.6 190 3650 male 2007
## 7 Adelie Torgersen 38.9 17.8 181 3625 fema… 2007
## 8 Adelie Torgersen 39.2 19.6 195 4675 male 2007
## 9 Adelie Torgersen 34.1 18.1 193 3475 <NA> 2007
## 10 Adelie Torgersen 42 20.2 190 4250 <NA> 2007
## # … with 334 more rows, and abbreviated variable names
## # ¹​bill_length_mm, ²​bill_depth_mm, ³​flipper_length_mm,
## # ⁴​body_mass_g
This is some text.
How do you get the table (penguins) that is output in the .md document to be wrapped in code ticks (```)?
At the moment, I can get it to work if I use:
---
output:
html_document:
keep_md: TRUE
---
In this example the .md that is generated and kept has all text output surrounded by code ticks. How do I get this without writing an html document?
I've tried updating the s3 object knit_print() but can't figure out how to get it to work. I've also tried various flavors of markdown and looked at pandoc add ons but can't figure it out. I've been googling for hours please help.

A simple approach is to provide a class to class.output chunk option, then the chunk output will be wrapped inside codeticks (triple backticks) automatically.
And to have this behavior for all output, add class.output="output" to knitr::opts_chunk$set.
---
title: 'This is a test title'
date: '`r Sys.Date()`'
output:
md_document:
variant: commonmark #or gfm
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
message = FALSE,
warning = FALSE,
class.output="output"
)
```
```{r echo=FALSE}
library(palmerpenguins)
```
```{r echo=TRUE}
penguins
```
```{r}
1 + 1
```
This is some text.
md output
``` r
penguins
```
``` output
## # A tibble: 344 × 8
## species island bill_length_mm bill_depth_mm flipper_…¹ body_…² sex year
## <fct> <fct> <dbl> <dbl> <int> <int> <fct> <int>
## 1 Adelie Torgersen 39.1 18.7 181 3750 male 2007
## 2 Adelie Torgersen 39.5 17.4 186 3800 fema… 2007
## 3 Adelie Torgersen 40.3 18 195 3250 fema… 2007
## 4 Adelie Torgersen NA NA NA NA <NA> 2007
## 5 Adelie Torgersen 36.7 19.3 193 3450 fema… 2007
## 6 Adelie Torgersen 39.3 20.6 190 3650 male 2007
## 7 Adelie Torgersen 38.9 17.8 181 3625 fema… 2007
## 8 Adelie Torgersen 39.2 19.6 195 4675 male 2007
## 9 Adelie Torgersen 34.1 18.1 193 3475 <NA> 2007
## 10 Adelie Torgersen 42 20.2 190 4250 <NA> 2007
## # … with 334 more rows, and abbreviated variable names ¹​flipper_length_mm,
## # ²​body_mass_g
```
``` r
1 + 1
```
``` output
## [1] 2
```
This is some text.

Feels a bit hacky, but you can cat the backticks as output to code chunks, but drop the comment symbol (##). (I'm using four backticks for the code blocks below to get the syntax highlighting correct)
````{r echo=FALSE, comment=NA}
cat('```')
````
````{r echo=FALSE}
penguins
````
````{r echo=FALSE, comment=NA}
cat('```')
````

Related

R tibbles not printing correctly in VS Code

I would like to use R tibbles in VS code but am seeing odd character formatting in tibble-output.
Take the penguins dataset from the palmgerpenguins package. The raw .csv looks like this:
"","species","island","bill_length_mm","bill_depth_mm","flipper_length_mm","body_mass_g","sex","year"
"1","Adelie","Torgersen",39.1,18.7,181,3750,"male",2007
"2","Adelie","Torgersen",39.5,17.4,186,3800,"female",2007
"3","Adelie","Torgersen",40.3,18,195,3250,"female",2007
"4","Adelie","Torgersen",NA,NA,NA,NA,NA,2007
"5","Adelie","Torgersen",36.7,19.3,193,3450,"female",2007
"6","Adelie","Torgersen",39.3,20.6,190,3650,"male",2007
When using R with VS Code, the output looks likes this:
library(palmerpenguins)
head(penguins)
# A tibble: 6 × 8
species island bill_length_mm bill_depth_mm flipper_l…¹ body_…² sex year
<fct> <fct> <dbl> <dbl> <int> <int> <fct> <int>
1 Adelie Torgersen 39.1 18.7 181 3750 male 2007
2 Adelie Torgersen 39.5 17.4 186 3800 fema… 2007
3 Adelie Torgersen 40.3 18 195 3250 fema… 2007
4 Adelie Torgersen NA NA NA NA NA 2007
5 Adelie Torgersen 36.7 19.3 193 3450 fema… 2007
6 Adelie Torgersen 39.3 20.6 190 3650 male 2007
# … with abbreviated variable names ¹​flipper_length_mm, ²​body_mass_g
This issue is only present on my work computer. My personal computer prints the tibble in VS code with the correct formatting.
I suspect the issue revolves around character encoding but I'm not sure what setting needs to be changed. My encoding settings in VS code are shown below. Any guidance on what features would need to be changed is much appreciated.

How to show rows that only contain N/A values in R?

I am having trouble writing a formula in R that allows me to output only rows that contain "N/A". I assuming filter_all would be included since this would be applied to all of the columns in the dataset but please let me know!
filter_all is deprecated. We can use filter with if_all
library(dplyr)
df1 %>%
filter(if_all(everything(), is.na))
If we are using the penguins dataset, not all columns have NAs
library(palmerpenguins)
data(penguins)
> colSums(is.na(penguins))
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g sex
0 0 2 2 2 2 11
year
0
i.e. 'species', 'island', 'year' have 0 NAs, so the above code with if_all returns 0 rows as a single row doesn't have all NA for all the columns. We may need if_any
penguins %>%
filter(if_any(everything(), is.na))
# A tibble: 11 × 8
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g sex year
<fct> <fct> <dbl> <dbl> <int> <int> <fct> <int>
1 Adelie Torgersen NA NA NA NA <NA> 2007
2 Adelie Torgersen 34.1 18.1 193 3475 <NA> 2007
3 Adelie Torgersen 42 20.2 190 4250 <NA> 2007
4 Adelie Torgersen 37.8 17.1 186 3300 <NA> 2007
5 Adelie Torgersen 37.8 17.3 180 3700 <NA> 2007
6 Adelie Dream 37.5 18.9 179 2975 <NA> 2007
7 Gentoo Biscoe 44.5 14.3 216 4100 <NA> 2007
8 Gentoo Biscoe 46.2 14.4 214 4650 <NA> 2008
9 Gentoo Biscoe 47.3 13.8 216 4725 <NA> 2009
10 Gentoo Biscoe 44.5 15.7 217 4875 <NA> 2009
11 Gentoo Biscoe NA NA NA NA <NA> 2009
Or if we want to check columns where there are at least one NA and returns the rows where they are all NA
penguins %>%
filter(if_all(where(~ any(is.na(.x))), is.na))
# A tibble: 2 × 8
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g sex year
<fct> <fct> <dbl> <dbl> <int> <int> <fct> <int>
1 Adelie Torgersen NA NA NA NA <NA> 2007
2 Gentoo Biscoe NA NA NA NA <NA> 2009

Error: Can't convert a `tbl_df/tbl/data.frame` object to function

penguins %>%
select(species,island,sex) %>%
rename(island_new=island) %>%
rename_with(penguins,toupper)
this is code which is causing error, can someone solve the problem
It's implied that the first argument of rename_with is what has been piped to it, so you don't need to pass penguins as the first argument:
penguins %>%
select(species,island,sex) %>%
rename(island_new=island) %>%
rename_with(toupper)
# A tibble: 344 x 3
SPECIES ISLAND_NEW SEX
<fct> <fct> <fct>
1 Adelie Torgersen male
2 Adelie Torgersen female
3 Adelie Torgersen female
4 Adelie Torgersen NA
5 Adelie Torgersen female
6 Adelie Torgersen male
7 Adelie Torgersen female
8 Adelie Torgersen male
9 Adelie Torgersen NA
10 Adelie Torgersen NA

Dynamically create and evaluate function in R

I am trying to dynamically create and evaluate a function from a string input and am hung up, again, on meta-programming/evaluation (https://adv-r.hadley.nz/metaprogramming.html). I have a feeling this is answered on SO, but I searched and wasn't able to figure out the solution looking through other posts; however, if there is an existing answer, please let me know and flag as duplicate. Thank you so much for your time and help! Below is a reprex of the issue.
library(dplyr)
library(purrr)
library(rlang)
library(palmerpenguins)
# Create data to join with penguins
penguin_colors <-
tibble(
species = c("Adelie", "Chinstrap", "Gentoo"),
color = c("orange", "purple", "green")
)
# Create function to do specified join and print join type
foo <- function(JOINTYPE) {
# DOESN'T RUN
# JOINTYPE_join(penguins, penguin_colors, by = "species")
# call2(sym(paste0(JOINTYPE, "_join")), x = penguins, y = penguin_colors, by = "species")
print(JOINTYPE)
}
# Desired behavior of foo when JOINTYPE == "inner"
inner_join(penguins, penguin_colors, by = "species")
#> # A tibble: 344 x 9
#> species island bill_length_mm bill_depth_mm flipper_length_… body_mass_g
#> <chr> <fct> <dbl> <dbl> <int> <int>
#> 1 Adelie Torge… 39.1 18.7 181 3750
#> 2 Adelie Torge… 39.5 17.4 186 3800
#> 3 Adelie Torge… 40.3 18 195 3250
#> 4 Adelie Torge… NA NA NA NA
#> 5 Adelie Torge… 36.7 19.3 193 3450
#> 6 Adelie Torge… 39.3 20.6 190 3650
#> 7 Adelie Torge… 38.9 17.8 181 3625
#> 8 Adelie Torge… 39.2 19.6 195 4675
#> 9 Adelie Torge… 34.1 18.1 193 3475
#> 10 Adelie Torge… 42 20.2 190 4250
#> # … with 334 more rows, and 3 more variables: sex <fct>, year <int>,
#> # color <chr>
print("inner")
#> [1] "inner"
# Use function in for loop
for (JOINTYPE in c("inner", "left", "right")) {
foo(JOINTYPE)
}
#> [1] "inner"
#> [1] "left"
#> [1] "right"
# Use function in vectorised fashion
walk(c("inner", "left", "right"), foo)
#> [1] "inner"
#> [1] "left"
#> [1] "right"
Created on 2020-10-27 by the reprex package (v0.3.0)
One option is to use get() to retrieve the appropriate function:
join <- function(JOINTYPE) {
get( paste0(JOINTYPE, "_join") )
}
join("inner")(penguins, penguin_colors, by="species")
If using rlang, the more appropriate function here is rlang::exec:
join2 <- function(JOINTYPE, ...) {
rlang::exec( paste0(JOINTYPE, "_join"), ... )
}
join2("inner", penguins, penguin_colors, by="species")

To add an indicator variable to a data frame

I wanted to add a new column called "Missing" to penguins data frame, so for any rows with at least an NA, I want to have TRUE in the Missing column and FALSE otherwise. My code just added all FALSE to the new column. How do I fix this? Thank you.
## install.packages("palmerpenguins")
library(palmerpenguins)
View(penguins)
penguins_m <- penguins %>%
mutate(Missing = ifelse(is.na(.),T,F))
species island bill_length_mm bill_depth_mm flipper_length_… body_mass_g sex year Missing[,"speci… [,"island"] [,"bill_length_… [,"bill_depth_m…
<fct> <fct> <dbl> <dbl> <int> <int> <fct> <int> <lgl> <lgl> <lgl> <lgl>
1 Adelie Torge… 39.1 18.7 181 3750 male 2007 FALSE FALSE FALSE FALSE
2 Adelie Torge… 39.5 17.4 186 3800 fema… 2007 FALSE FALSE FALSE FALSE
3 Adelie Torge… 40.3 18 195 3250 fema… 2007 FALSE FALSE FALSE FALSE
4 Adelie Torge… NA NA NA NA NA 2007 FALSE FALSE TRUE TRUE
5 Adelie Torge… 36.7 19.3 193 3450 fema… 2007 FALSE FALSE FALSE FALSE
6 Adelie Torge… 39.3 20.6 190 3650 male 2007 FALSE FALSE FALSE FALSE
This is what the complete.cases function does, so you can do
penguins_m <- penguins %>%
mutate(Missing = !complete.cases(.))
A couple comments on your attempt - when you have a function or test that returns TRUE or FALSE, you don't need to wrap it in ifelse to get a TRUE/FALSE result.
Your attempt doesn't work because is.na(x) doesn't return 1 value per row if x is a data frame - it actually returns a matrix of TRUE/FALSE values showing whether each individual value is missing or not. So, if we didn't know about complete.cases we could use it like this:
penguins_m <- penguins %>%
mutate(Missing = rowSums(is.na(.)) > 0)

Resources