I am trying to get my head around using loops in R so that I can avoid the repetitive code I used to format a table.
I'm just starting the process of learning loops to automate tasks, so there's been mostly blank stares up to this point. The long version of the code I used does the job, but wouldn't be practical on a larger scale.
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"))
The code I came up with does the job but is very repetitive. I've been trying to figure out how to either get a loop to run the formatStyle() function over every column in the table, or find some other function that performs the same task, but haven't had any success.
datatableandformatStylecome from?