样本数据(修改自formattable
github 文档):
df <- data.frame(
id = 1:10,
name = c("Bob", "Ashley", "James", "David", "Jenny",
"Hans", "Leo", "John", "Emily", "Lee"),
age = c(48, 47, 40, 28, 29, 29, 27, 27, 31, 30),
test1_score = c(18.9, 19.5, 19.6, 12.9, 11.1, 7.3, 4.3, 3.9, 2.5, 1.6),
test2_score = c(9.1, 9.1, 9.2, 11.1, 13.9, 14.5, 19.2, 19.3, 19.1, 18.8),
stringsAsFactors = FALSE)
您可以使用额外的颜色格式制作一个漂亮的表格,如下所示:
library(formattable)
formattable(df, list(
age = color_tile("white", "orange"),
test1_score = color_bar("pink", 0.2),
test2_score = color_bar("pink", 0.2)
))
看起来像这样:
我现在想做的是过滤这个表,这样我只保留前 n 行 - 这里 n=3。不这样做的方法是进行典型的子集化,因为色标现在仅应用于数据子集的最小/最大,而不是原始数据。 IE。
formattable(df[1:3,], list(
age = color_tile("white", "orange"),
test1_score = color_bar("pink", 0.2),
test2_score = color_bar("pink", 0.2)
))
这看起来像这样:
这显然重新调整了颜色。
看着str
对象的:
str(
formattable(df, list(
age = color_tile("white", "orange"),
test1_score = color_bar("pink", 0.2),
test2_score = color_bar("pink", 0.2)
))
)
Classes ‘formattable’ and 'data.frame': 10 obs. of 5 variables:
$ id : int 1 2 3 4 5 6 7 8 9 10
$ name : chr "Bob" "Ashley" "James" "David" ...
$ age : num 48 47 40 28 29 29 27 27 31 30
$ test1_score: num 18.9 19.5 19.6 12.9 11.1 7.3 4.3 3.9 2.5 1.6
$ test2_score: num 9.1 9.1 9.2 11.1 13.9 14.5 19.2 19.3 19.1 18.8
- attr(*, "formattable")=List of 4
..$ formatter: chr "format_table"
..$ format :List of 1
.. ..$ :List of 3
.. .. ..$ age :function (x)
.. .. ..$ test1_score:function (x)
.. .. ..$ test2_score:function (x)
..$ preproc : NULL
..$ postproc : NULL
由于结构包含其他元素,因此不可能仅过滤/子集生成的对象。
有没有办法只输出前 n 行以及使用整个表/数据框时它们将具有的色标?