Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

r - How to use mathematical notation or engineering notation in certain columns of a kableExtra table?

One can apply docxtools::format_engr() to a table to switch from computer notation to engineering notation.

NotationTypes (Source: docxtools)

Applying docxtools::format_engr() to a df changes all columns to engineering notation.

  1. How to apply the function only to some columns of a df?
  2. Is there an equivalent function for mathematical notation?

For the toy example below, the idea would be to get the p_Pa column in engineering/mathematical notation, while all other columns remain the same.

MWE

Table as desired only missing the p_Pa column in engineering notation

library(docxtools)
density2 <- density
density2$density <- density2$density*1000
kable(density2, digits = 2)

GOAL

Apply formatting: "all" columns change to engineering notation

# Apply formatting:
density_engr <- density2 %>%
  docxtools::format_engr()
kable(density_engr)

All get exponentiated

Passing sigdig() to docxtools::format_engr() (e.g., sth. like "sigdig = c(0,0,2,3,2,3)") to define how to format which column does not help here. Engineering notation is still applied to ALL columns, only with differing numbers of digits.

The idea is to include the df as kableExtra table in an R markdown report compiled with knitr both to PDF and HTML.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a dataframe that contains only the columns you want formatted, format that, and then assign it into place in the original. For example, starting with your density2:

density_engr <- density2        # no formatting yet
do_format <- c("T_K", "p_Pa")   # which columns to format?
density_engr[do_format] <- docxtools::format_engr(density_engr[do_format])

There are other ways to do the indexing besides density_engr[do_format], but be careful: you want to make sure you get a dataframe as the result, you don't want to extract a column.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...