r - 在 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() 函数,或者找到执行相同任务但没有任何成功的其他一些函数。
解决方案
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")))
推荐阅读
- go - sync.Pool 比使用 channel 慢很多,那我们为什么要使用 sync.Pool 呢?
- excel - 如何在excel公式中实现以下
- plsql - 联合所有运算符的混乱
- apache - 使用 htaccess 重写规则
- php - ajax响应后有url重定向
- swift - 转换为协议时未调用协议扩展方法
- android - 当应用程序在 Nougat(版本 25)事件中从后台清除时,服务未运行,尽管我使用了 startforegound 通知
- http - 使用 ionic 向 iis 服务器发出 http 请求时出现未知的 http 错误
- aql - QRAdar - AQL 在输入 SELECT 处没有可行的替代方案
- angular - Angular Unit test - 如何在商店调度期间模拟由ngrx / effect调用的组件中的提供者