问题描述
我想根据以下规则将不同颜色的文本添加到日期框或 HTML 表格中(能够定时破解变量)
即时 = 红色文本,秒 = 橙色文本,分钟 - 黄色文本,年 = 绿色文本。
我的数据框是
> dput(Final_DF)
structure(list(gender = c("female","male","female","male"),age = structure(c(47L,43L,65L,24L,44L,60L,26L,25L,62L,23L,61L,27L,47L,18L,34L,77L,71L,19L,64L,22L,55L,45L,29L,21L,20L,32L,68L,81L,63L,72L,38L,66L,39L,73L,53L,75L,69L,82L),class = c("variable","integer"
),varname = "Age"),web_browser = structure(c(1L,1L,4L,3L,2L,1L),.Label = c("Chrome","Internet Explorer","Firefox","netscape"),"factor"),varname = "browser"),Pswd = c("Password","abc1","football","Pr?hStMz3xuJ","Strawberries","JTA9sstLjU","Jazzed!","D!gU4","12345!","mQf0J?2","password1","CATS?","F!!FtBm","!!!!","HBpqA?xya9SIi","Os4Ft%D","fryj0t9KS","monkey","shadow","gpbvYZxYLBq7P","blackberries","Abc1!","p0$YpH4","SLOTH","Qwertyuiop","SqbmZZ!abHj","?Lnp6X6TNz","boatstatecat","shearer9","1B!aKnQm","DOGS","sunshine","pgJz8!Hdde","qwerty","1q2w3e4r5t","flightrockcups","ashley","Htkv5TDS51","C8cFMWH?a$S","cheesesteak","password!","aircraft","Se3PKKeg?dU","iloveyou","Bug!5$r","123","dragon","superman","password"),pswd_length = c(8L,8L,12L,10L,7L,5L,6L,9L,13L,11L,14L,8L),Time_to_crack = c("instant","instant","857 billion years","0.84 seconds","0.02 seconds","4.71 seconds","5.46 minutes","111 years","6.11 seconds","23 days","0.1 seconds","393 million years","3 months","49 years","81 trillion years","43.7 seconds","19.62 seconds","12 years","1.58 seconds","0.15 seconds","23 thousand years","2 million years","11 hours","5.81 seconds","1 year","4 thousand years","0.09 seconds","4 million years","0.34 seconds","23 hours","41 centuries","14 thousand years","11.26 seconds","0.3 seconds","8 thousand years","4 hours","instant")),row.names = c(NA,-50L),class = "data.frame")
我找到了这个formatable data frame walkthrough,but not sure how to apply it to my scenario
解决方法
这可以像这样实现:
- 在小插图之后使用
ifelse
或使用例如定义格式化程序函数dplyr::case_when
定义了要应用的条件样式。 - 在
formattable
中将此格式化程序应用于您的列Time_to_crack
library(formattable)
library(dplyr)
time_formatter <- formatter("span",style = x ~ style(color = dplyr::case_when(
grepl("(instant|seconds)",x) ~ "red",grepl("(months|years)",x) ~ "green",grepl("hours",x) ~ "yellow",grepl("minutes",x) ~ "orange",TRUE ~ "black")))
formattable(Final_DF,list(Time_to_crack = time_formatter))