首页 > 解决方案 > 在 R 中创建循环以避免重复代码

问题描述

我正在尝试在 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() 函数,或者找到执行相同任务但没有任何成功的其他一些函数。

标签: rloopsfor-loop

解决方案


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")))

推荐阅读