Kable table R:粗体对角线单元格
Kable table R: diagonal cells in bold
假设我有一个数据 table:
lttrs <- c('a', 'b', 'c')
a <- c(5, 9, 2)
b <- c(3, 3, 8)
c <- c(14, 2, 0)
df <- as.data.table(cbind(lttrs, a, b, c))
view(df)
lttrs a b c
1: a 5 3 14
2: b 9 3 2
3: c 2 8 0
现在我想用 kable 做一个 table 像这样:
tableDf <- df[]%>%
select(everything())%>%
kable("html", escape = F) %>%
kable_styling(bootstrap_options = "striped", full_width = F, position = "left")
给我下图
我希望 (5, 3, 0) 中的对角线值加粗。我想我必须使用 cell_spec 并且必须创建 df$lttrs == colnames(df) 的条件,但是,我还没有设法解决这个问题。有人有解决办法吗?
我们可以使用 library(kableExtra)
中的 cell_spec
for (i in df[, seq_len(.N)]) {
df[i, i+1L] <- cell_spec(df[i, i+1L, with=F], "html", bold=T)
}
kable(df, "html", escape = F) %>%
kable_styling(bootstrap_options = "striped", full_width = F)
如果你真的想让事情脱颖而出,你也可以改变颜色和字体等。例如,
for (i in df[, seq_len(.N)]) {
df[i, i+1L] <- cell_spec(df[i, i+1L, with=F], "html", bold=T, background = "red", color = "white")
}
建立在@dww 提供的很好的答案的基础上,如果您在 table 中不使用整数,则稍作调整:
library(kableExtra)
# build the df with non-integers
lttrs <- c('a', 'b', 'c')
a <- c(5.2, 9, 2)
b <- c(3, 3, 8.4)
c <- c(14.3, 2, 0.7)
df <- as.data.frame(cbind(a, b, c))
rownames(df) <- lttrs
# colorize the diagonal elements in table with non-ints
for (i in 1:(ncol(df))) {
df[i,i] <- cell_spec(df[i, i], bold=T, color = "orange", background = "lightgray")
}
# print table, e.g., in html format
kable(df, "html", escape = F) %>%
kable_styling(bootstrap_options = "striped", full_width = F)
假设我有一个数据 table:
lttrs <- c('a', 'b', 'c')
a <- c(5, 9, 2)
b <- c(3, 3, 8)
c <- c(14, 2, 0)
df <- as.data.table(cbind(lttrs, a, b, c))
view(df)
lttrs a b c
1: a 5 3 14
2: b 9 3 2
3: c 2 8 0
现在我想用 kable 做一个 table 像这样:
tableDf <- df[]%>%
select(everything())%>%
kable("html", escape = F) %>%
kable_styling(bootstrap_options = "striped", full_width = F, position = "left")
给我下图
我希望 (5, 3, 0) 中的对角线值加粗。我想我必须使用 cell_spec 并且必须创建 df$lttrs == colnames(df) 的条件,但是,我还没有设法解决这个问题。有人有解决办法吗?
我们可以使用 library(kableExtra)
cell_spec
for (i in df[, seq_len(.N)]) {
df[i, i+1L] <- cell_spec(df[i, i+1L, with=F], "html", bold=T)
}
kable(df, "html", escape = F) %>%
kable_styling(bootstrap_options = "striped", full_width = F)
如果你真的想让事情脱颖而出,你也可以改变颜色和字体等。例如,
for (i in df[, seq_len(.N)]) {
df[i, i+1L] <- cell_spec(df[i, i+1L, with=F], "html", bold=T, background = "red", color = "white")
}
建立在@dww 提供的很好的答案的基础上,如果您在 table 中不使用整数,则稍作调整:
library(kableExtra)
# build the df with non-integers
lttrs <- c('a', 'b', 'c')
a <- c(5.2, 9, 2)
b <- c(3, 3, 8.4)
c <- c(14.3, 2, 0.7)
df <- as.data.frame(cbind(a, b, c))
rownames(df) <- lttrs
# colorize the diagonal elements in table with non-ints
for (i in 1:(ncol(df))) {
df[i,i] <- cell_spec(df[i, i], bold=T, color = "orange", background = "lightgray")
}
# print table, e.g., in html format
kable(df, "html", escape = F) %>%
kable_styling(bootstrap_options = "striped", full_width = F)