不知道大家有没有发现在很多网页中会有很多漂亮的表格,那么今天我们就来看下在R语言中如何实现网页交互式表格的绘制。首先,我们来看下实现这个功能的R包“formattable”。它的安装可以直接install.packages(“formattable”)即可。
接下来我们看下其主要的函数:
1. formattable 创建表格对象,并展示其可视化结果。其在文档中说明很简单,但是其中一个list参数可以挨个去设置每列的可视化形式。
参考自《简书》的一个实例程序如下:
library(formattable)
#构建数据
df <- data.frame(
id= 1:10,
name = c("Bob", "Ashley", "James","David", "Jenny",
"Hans", "Leo", "John", "Emily","Lee"),
age= c(28, 27, 30, 28, 29, 29, 27, 27, 31, 30),
grade = c("C", "A", "A", "C","B", "B", "B", "A", "C","C"),
test1_score = c(8.9, 9.5, 9.6, 8.9, 9.1, 9.3, 9.3, 9.9, 8.5, 8.6),
test2_score = c(9.1, 9.1, 9.2, 9.1, 8.9, 8.5, 9.2, 9.3, 9.1, 8.8),
final_score = c(9, 9.3, 9.4, 9, 9, 8.9, 9.25, 9.6, 8.8, 8.7),
registered = c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE,FALSE),
stringsAsFactors = FALSE)
# 数据预览
df
# id name age grade test1_scoretest2_score final_score registered
# 1 1 Bob 28 C 8.9 9.1 9.00 TRUE
# 2 2 Ashley 27 A 9.5 9.1 9.30 FALSE
# 3 3 James 30 A 9.6 9.2 9.40 TRUE
# 4 4 David 28 C 8.9 9.1 9.00 FALSE
# 5 5 Jenny 29 B 9.1 8.9 9.00 TRUE
# 6 6 Hans 29 B 9.3 8.5 8.90 TRUE
# 7 7 Leo 27 B 9.3 9.2 9.25 TRUE
# 8 8 John 27 A 9.9 9.3 9.60 FALSE
# 9 9 Emily 31 C 8.5 9.1 8.80 FALSE
# 10 10 Lee 30 C 8.6 8.8 8.70 FALSE
# 指定表格可视化颜色
# age以渐变的形式呈现的
# grade中所有A背景为绿色.
# test1_score 和test2_score以水平的柱状形式展示,背景:低分的为白色,高分的为粉色
# final_score 展示分值和等级,位于前三的字体显示为绿色,其他的为灰色
# registered 文本替换为yes或者no来展示
As=formattable(df, list(
age= color_tile("white", "orange"), ## 白色到橘色渐变
grade = formatter("span", style = x ~ ifelse(x =="A",
style(color = "green", font.weight = "bold"), NA)),## 如果为A就为绿色,字体为bold,否则不改变
area(col = c(test1_score, test2_score)) ~ normalize_bar("pink",0.2), ## test1 和test2背景填充为粉色,并且以数值大小来表示柱子的长度
final_score = formatter("span",
style = x ~ style(color = ifelse(rank(-x) <= 3, "green","gray")),
x~ sprintf("%.2f (rank: d)", x, rank(-x))),
registered = formatter("span",
style = x ~ style(color = ifelse(x, "green","red")),
x~ icontext(ifelse(x, "ok", "remove"), ifelse(x,"Yes", "No")))
))
2. as.datatable 创建动态的交互网页表格。
示例程序如下:
as.datatable(as)
3. formattableOutput 输出图像的CSS代码
示例程序如下:
formattableOutput(as)
这个看似天书的东西就是CSS样式,那么把他粘到HTML中效果就和它自带函数实现的样子一样了。