我试图让我的头周围使用R中循环,使我能避免我用来格式化表格重复代码。
我刚开始学习的过程中循环自动执行任务,所以一直主要是空洞的眼神了这一点。我使用的代码的长版本做这项工作,但不会实际在更大的规模。
library(DT)
## Create data frame containing test results for Students A - H.
A <- c(69, 64, 70, 57, 80, 34, 45, 56, 96)
B <- c(70, 74, 68, 76, 71, 56, 56, 45, 30)
C <- c(84, 58, 87, 78, 67, 67, 43, 34, 56)
D <- c(78, 83, 68, 72, 90, 48, 23, 23, 46)
E <- c(79, 55, 91, 71, 34, 26, 76, 67, 75)
F <- c(80, 72, 64, 45, 66, 76, 45, 56, 54)
G <- c(90, 67, 76, 51, 45, 59, 33, 64, 34)
H <- c(60, 59, 88, 90, 76, 34, 43, 72, 45)
student_results <- data.frame(A, B, C, D, E, F, G, H)
## Create table of data frame, highlighting marks >= 85 in 'aquamarine'
## Marks < 50 highlighted in 'coral'
datatable(student_results) %>%
formatStyle('A',
backgroundColor = styleInterval(c(50,85), c("coral", "white", "aquamarine"))) %>%
formatStyle('B',
backgroundColor = styleInterval(c(50,85), c("coral", "white", "aquamarine"))) %>%
formatStyle('C',
backgroundColor = styleInterval(c(50,85), c("coral", "white", "aquamarine"))) %>%
formatStyle('D',
backgroundColor = styleInterval(c(50,85), c("coral", "white", "aquamarine"))) %>%
formatStyle('E',
backgroundColor = styleInterval(c(50,85), c("coral", "white", "aquamarine"))) %>%
formatStyle('F',
backgroundColor = styleInterval(c(50,85), c("coral", "white", "aquamarine"))) %>%
formatStyle('G',
backgroundColor = styleInterval(c(50,85), c("coral", "white", "aquamarine"))) %>%
formatStyle('H',
backgroundColor = styleInterval(c(50,85), c("coral", "white", "aquamarine"))
我想出了代码执行的工作,但很重复。我一直在试图找出如何要么得到一个循环表中碾过每一行的formatStyle()函数,或查找执行相同任务的一些其他功能,但都没有成功。
管道a %>% b() %>% b() %>% b()
是一样的反复评估b(b(b(a)))
,所以你for
循环版本看起来像你的函数重复应用:
> sr = datatable(student_results)
> for(L in LETTERS[1:8]){
sr = formatStyle(sr, L,
backgroundColor = styleInterval(
c(50,85), c("coral", "white", "aquamarine")))}
> sr
library(DT)
#colnames(student_results)[2:ncol(student_results)] #if you need selected columns
datatable(student_results) %>%
formatStyle(colnames(student_results),backgroundColor = styleInterval(c(50,85), c("coral", "white", "aquamarine")))