示例:我有一个简单的数据框
df <- data.frame(date=c("2016-01-01", "2016-01-02")
, sales_a = c(2,3)
, sales_b = c(1,1)
, diff=c(1,2))
Run Code Online (Sandbox Code Playgroud)
我目前正在RMarkDown文档中使用kable打印此df.我想用下面的行(不是日期)和一条将df与总数分开的行生成一行.如果没有编写我不太熟悉的乳胶代码,可以使用任何R包吗?
谢谢
我不认为你可以在markdown中的最后一行和倒数第二行之间划一条线.但计算和包括摘要行相对简单.
(顺便说一句:我已经包含stringsAsFactors在data.frame中,因为它更喜欢并且易于处理新字符串.)
df <- data.frame(date=c("2016-01-01", "2016-01-02")
, sales_a = c(2,3)
, sales_b = c(1,1)
, diff=c(1,2)
, stringsAsFactors = FALSE)
func <- function(z) if (is.numeric(z)) sum(z) else ''
sumrow <- as.data.frame(lapply(df, func))
sumrow
# date sales_a sales_b diff
# 1 5 2 3
Run Code Online (Sandbox Code Playgroud)
与整个data.frame结合起来相对简单:
library(knitr)
kable(rbind(df, sumrow))
# |date | sales_a| sales_b| diff|
# |:----------|-------:|-------:|----:|
# |2016-01-01 | 2| 1| 1|
# |2016-01-02 | 3| 1| 2|
# | | 5| 2| 3|
Run Code Online (Sandbox Code Playgroud)
如果您希望能够突出显示/标记特定摘要行:
kable(rbind(cbind(' '=' ', df),
cbind(' '='Total', sumrow)))
# | |date | sales_a| sales_b| diff|
# |:-----|:----------|-------:|-------:|----:|
# | |2016-01-01 | 2| 1| 1|
# | |2016-01-02 | 3| 1| 2|
# |Total | | 5| 2| 3|
Run Code Online (Sandbox Code Playgroud)
"Total"标签当然可以放在任何地方.您可能会尝试手动添加一行(字符),但我不确定它是否正确.
我以/sf/answers/2524871051/的答案为灵感,使用 RStudio 在 R 中创建以下内容。然后可以根据需要将表格导出(knit)为 pdf/html。
现在看代码...
```{r name-of-chunk, echo=FALSE}
# Load packages
library(dplyr)
library(kableExtra)
# Make lists
types <- c("Heating", "Water Heating", "Electricity")
heat_per_person <- c (9.59, 1.32, 1.95)
heat_per_area <- c(95.26, 13.55, 20.03)
# Make dataframe
results_df <- data.frame(types , heat_per_person, heat_per_area, stringsAsFactors = FALSE)
# Sum the last row of each column if numeric
func <- function(z) if (is.numeric(z)) sum(z) else ''
sumrow <- as.data.frame(lapply(results_df, func))
# Give name to the first element of the new data frame created above
sumrow[1] <- "Total"
# Add the original and new data frames together
summed_results_df <- rbind(results_df, sumrow)
# Name the columns
colnames <- data.frame("Service", "Amount per Person","Amount per Area", stringsAsFactors = FALSE)
colnames(summed_results_df) <- colnames
# Make Table
kable(summed_results_df, caption = "Normalized Annual Energy Demand", booktabs = TRUE) %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed")) %>%
row_spec(dim(summed_results_df)[1], bold = T) %>% # format last row
column_spec(1, italic = T) # format first column
```
Run Code Online (Sandbox Code Playgroud)
您可以参考 Rmarkdown/Rmd 文本中的表格以及代码块的名称,如下所示:\@ref(tab:name-of-chunk)
| 归档时间: |
|
| 查看次数: |
3227 次 |
| 最近记录: |