2017-04-10 96 views
0

我有這個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')) 

回答

0

您可以通過在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')) 
) 
``` 

表看起來是這樣的: enter image description here

相關問題