我创建了一个表,该表包含一些生产数据,预测数据以及两者之间的差异。对于这些类别,我想同时显示6年。如果我突然改为3年而不是6年,我会努力使每个类别的标签都可以适应。
我的代码:
proddata <- read.table("C:/...Production.csv",sep=";" , header=TRUE)
forcdata <- read.table("C:...Forecast.csv", sep=";",header=TRUE)
wells<-unique(proddata[3]) mergedAll<-NULL
for (i in 1:length(wells[[1]])){
prod_w<-subset(proddata,Well ==wells[i,1])
forc_w<-subset(forcdata,Well ==wells[i,1])
t_prod<-t(prod_w[,c(1,2)]) t_forc<-t(forc_w[,c(1,2)])
delta<-t_prod[c(1,2),]
delta[2,]<-as.numeric(t_prod[2,])-as.numeric(t_forc[2,])
merged<- data.frame(t_prod[c(1,2),] ,t_forc[c(1,2),] ,delta)
colnames(merged) <- merged[1, ] merged <- merged[-1, ]
rownames(merged)<-wells[i,1]
if (!exists("mergedAll")){ mergedAll<-merged } else {
mergedAll<-rbind(mergedAll,merged) } }
library(gridExtra) grid.table(mergedAll)
这是我想要的:
Dynamic labels above the table
最佳答案
您可以为此使用tableHTML
。
示例数据
df <- structure(list(X2014 = c(10L, 101L, 111L), X2015 = c(20L, 202L,
212L), X2016 = c(30L, 303L, 313L), X2017 = c(40L, 404L, 414L),
X2018 = c(50L, 505L, 515L), X2019 = c(50L, 506L, 516L), X2014.1 = c(12L,
112L, 122L), X2015.1 = c(18L, 118L, 128L), X2016.1 = c(41L,
141L, 132L), X2017.1 = c(60L, 160L, 151L), X2018.1 = c(55L,
155L, 170L), X2019.1 = c(-2L, -11L, -11L), X2014.2 = c(2L,
84L, 84L), X2015.2 = c(-11L, 162L, 181L), X2016.2 = c(-20L,
244L, 263L), X2017.2 = c(-5L, 350L, 345L), X2018.2 = c(52L,
517L, 527L), X2019.2 = c(10L, 28L, 38L)), .Names = c("X2014",
"X2015", "X2016", "X2017", "X2018", "X2019", "X2014.1", "X2015.1",
"X2016.1", "X2017.1", "X2018.1", "X2019.1", "X2014.2", "X2015.2",
"X2016.2", "X2017.2", "X2018.2", "X2019.2"), class = "data.frame", row.names = c("W1",
"W2", "W3"))
基本解决方案
设置这样的动态输入:
years
是数据帧中的年份(注意:如果您的数据结构允许重复的列名,则也可以使用unique(names(df))
获得相同的结果)。 num_years
对它们进行计数,因此您可以更改输入。 num_cols
是tableHTML
对象的列数。years <- 2014:2019
num_years <- length(years)
num_cols <- 1 + num_years * 3
library(tableHTML)
这将创建一个
tableHTML
,其中year为标题,标签为标题上方的第二个标题。df %>%
tableHTML(headers = rep(years, 3),
second_headers = list(c(1, rep(num_years, 3)),
c("", "Production", "Forecast", "Difference")),
widths = rep(100, num_cols))
结果看起来像这样:
添加CSS以格式化表格:
您可以使用add_css_ *系列函数来设置
tableHTML
的样式:df %>%
tableHTML(headers = rep(years, 3),
second_headers = list(c(1, rep(num_years, 3)),
c("", "Production", "Forecast", "Difference")),
widths = rep(100, num_cols)) %>%
add_css_header(css = list("background-color",
"gray"),
headers = 1:num_cols) %>%
add_css_second_header(css = list("background-color",
"gray"),
second_headers = 1:num_cols) %>%
add_css_row(css = list("background-color",
"darkgray"),
rows = 4) %>%
add_css_row(css = list("background-color",
"lightgray"),
rows = c(3, 5))
结果将是: