我需要能够减少或简化此表中的数字。我只希望显示最多4个小数位,并且如果数字是整数,则只希望整数。我该怎么办?
library(kableExtra)
x = c(1, 1, 1, 1, 1, 1, 1, 1, 1)
y = x/2
z = x/3
a = data.frame(x, y, z)
b = t(a)
c = kable(b, "html", align = "c") %>%
kable_styling(full_width = F)
答案 0 :(得分:0)
使用format()
函数将数据转换为呈现数据所需的最小小数位数。使用原始帖子中的代码:
library(knitr)
library(kableExtra)
x = c(1, 1, 1, 1, 1, 1, 1, 1, 1)
y = x/2
z = x/3
a = data.frame(x = format(x,digits=4,nsmall = 0),
y = format(y,digits=4,nsmall = 0),
z = format(z,digits = 4,nsmall = 0))
b = t(a)
c = kable(b, "html", align = "c") %>%
kable_styling(full_width = F)
...以及输出:
结合Martin Schmelzer的评论,同一解决方案的简化版本看起来像这样。
# tidyverse alternative
library(knitr)
library(kableExtra)
library(dplyr)
x = c(1, 1, 1, 1, 1, 1, 1, 1, 1)
y = x/2
z = x/3
data.frame(x,y,z) %>%
mutate_if(is.numeric, format, digits=4,nsmall = 0) %>% t(.) %>% kable(.,"html",align = "c") %>%
kable_styling(full_width = F) -> c