簡體   English   中英

R - 打印列總和如下表

[英]R - Print table with columns sums below

示例:我有一個簡單的數據框

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

我目前正在 RMarkDown 文檔中使用 kable 打印此 df。 我想在下面生成一行,其中包含列的總和(不是日期),並用一條線將 df 與總數分開。 這是否可以在任何 R 包中實現,而無需編寫我不太熟悉的乳膠代碼?

謝謝

我認為你不能在 Markdown 的最后一行和倒數第二行之間畫一條線。 但是計算和包括匯總行相對簡單。

(順便說一句:我已經在stringsAsFactors中包含了 stringsAsFactors,為了優先和易於處理新字符串。)

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

與整個 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|

如果您希望能夠突出顯示/標記特定的摘要行:

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|

“總計”標簽當然可以放在任何地方。 您可能會嘗試手動添加一行(字符),但我不確定它看起來是否正確。

我以https://stackoverflow.com/a/36069586/8076560的答案為靈感,使用 RStudio 在 R 中創建以下內容。 然后可以根據需要將表格導出(編織)為 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

```

您可以使用代碼塊的名稱來引用 Rmarkdown/Rmd 文本中的表格,如下所示: \\@ref(tab:name-of-chunk)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM