R - 打印表,列总和低于

时间:2016-03-17 17:22:56

标签: r

示例:我有一个简单的数据框

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包吗?

由于

2 个答案:

答案 0 :(得分:6)

我认为你不能在降价中的最后一行和倒数第二行之间划一条线。但计算和包括摘要行相对简单。

(顺便说一句:我在data.frame中包含了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|

“Total”标签当然可以放在任何地方。您可能会尝试手动添加一行(字符),但我不确定它看起来是否正确。

答案 1 :(得分:1)

我以https://stackoverflow.com/a/36069586/8076560的答案为灵感,使用RStudio在R中创建了以下内容。然后可以根据需要将该表导出(编织)到pdf / html。

Screenshot of Finished Table

现在输入代码...

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