R可格式化包 - 通过包含字符向量的列中的行值更改颜色
问题描述:
我有这个data.frame,我想使用formattable包为每个名称分配不同的颜色,即“Bob”=“Blue”,“阿什利“=”红“等任何想法?R可格式化包 - 通过包含字符向量的列中的行值更改颜色
我刚刚开始使用r编程,但由于有很少的例子,文档专注于数值,所以我特别在格式化包中苦苦挣扎。
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)
我到目前为止,有一个值,但与其他strugling:
name = formatter("span", style = x ~ ifelse(x == "Bob",
style("background-color" = "blue", display = "block", "border-radius" = "4px", font.weight = "bold"), NA))))
我怎么从柱就像你可以在DT包formatStyle做添加其他参数。
%>%
formatStyle(
'name',
backgroundColor = styleEqual(c('Bob', 'Ashley'), c('blue', 'red'))
答
您可以通过在formatStyle()
使用参数target = 'row'
风格的整行而不是单个单元格。
这里是.Rmd代码块:
```{r data}
library(formattable)
library(DT)
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)
datatable(df) %>% formatStyle(
'name',
target = 'row',
backgroundColor = styleEqual(c("Bob", "Ashley"), c('blue', 'red'))
)
```