我有这个data.frame,我想使用formattable包为每个名称指定不同的颜色,其中“Bob”=“Blue”,“Ashley”=“Red”等等。有什么想法吗?
我刚开始使用r编程,但我特别在使用formattable包,因为很少有示例,文档主要关注数值。
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)
到目前为止,我得到了一个值,但与其他人争吵:
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'))
答案 0 :(得分:0)
您可以使用target = 'row'
中的参数formatStyle()
设置整行的样式而不是单个单元格。
这是.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'))
)
```