代码在R脚本中打印表,但在RMarkdown中返回NULL错误

g6ll5ycj  于 2023-05-11  发布在  其他
关注(0)|答案(1)|浏览(147)

这是我的代码:

```{r}
library (gt)
library(tidyverse)
library(measurements)
library(lubridate)
library(readxl)
library(ggplot2)
library(dplyr)
solar_data <- read_excel("SolarRadiationAthens.xlsx")
panel_size <- 32 # in square meters
efficiency <- 0.2 # 20% efficiency
solar_data <- solar_data %>%
  mutate(day_energy = SolarWatt * panel_size * efficiency / 1000) %>%
  group_by(month = month(Timestamp)) %>%
  summarise(avg_energy = mean(day_energy))
solar_table <- gt(solar_data) %>%
  tab_header(title = "Average Daily Electricity Generated by Month") %>%
  cols_label(month = "Month", avg_energy = "Electricity Generated (kWh)") %>%
  fmt_number(columns = c(avg_energy), decimals = 2)
print(solar_table)

在RMarkdown中,print函数返回NULL错误。保存为PDF时,将生成10页##文本,如下所示:

![](https://i.stack.imgur.com/2JQ6C.png)

同样的代码在R脚本中也能很好地工作。有什么问题吗?
ffscu2ro

ffscu2ro1#

问题是您使用print()来呈现表。若要修复此问题,请直接渲染表而不将其保存为变量,或者在渲染为PDF时使用as_latex()
使用基于mtcars的最小可重复示例。
首先,让我们重现您的问题:

---
title: "Untitled"
output: pdf_document
date: "2023-05-05"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(gt)

solar_table <- gt(mtcars) %>%
  tab_header(title = "Average Daily Electricity Generated by Month")

print(solar_table)

![](https://i.stack.imgur.com/RIogD.png)

其次,使用`as_latex`代替`print()`:
library(gt)

solar_table <- gt(mtcars) %>%
  tab_header(title = "Average Daily Electricity Generated by Month")

as_latex(solar_table)

![](https://i.stack.imgur.com/x6q8y.png)

相关问题