如何根据 R Shiny DT 中的模式突出显示每个单元格包含单个字符的行中的一堆相邻单元格
How to highlight bunch of adjacent cells in a row containing single character per cell based on a pattern in R Shiny DT
此查询是对我之前在本论坛中的 的扩展。但是,这次我必须处理一行中的一系列字符,每个字符都在一个单元格中,如下图所示。我想根据以下模式突出显示或更改某些单元格的背景:
任何包含字母的相邻单元格,例如 A?C
,其中 ?
可以是任何字母或
仅 M
在一个单元格中或
相邻单元格中的 N 和 F,例如 NF
,如下图所示。
也就是说,需要把这个table转换成
这在 R Shiny DT 中使用 rowCallback 函数。
我在这里拉我的包,所以这对你来说可能不合适,因为它只使用 HTML table 而不是 DT,并且在 R 端工作而不是在 javascript.
find_pattern <- function (pat, mat) {
# collapse the row into a single string:
strings <- apply(mat, 1, paste0, collapse = '')
# find the patterns you want:
found <- gregexpr(pat, strings, perl = TRUE)
# the rest is just housekeeping:
pos <- matrix(FALSE, nrow(mat), ncol(mat))
lapply(seq_along(found), function (x) {
matches <- found[[x]]
lens <- attr(matches, 'match.length')
if (all(matches == -1)) return()
for (p in seq_along(matches)) {
start <- matches[p]
len <- lens[p]
end <- start + len - 1
pos[x, start:end] <<- TRUE
}
})
which(pos, arr.ind = TRUE)
}
library(huxtable)
mydata <- matrix(sample(c('A', 'B', 'C', 'M', 'N', 'F'), 750, replace=TRUE), 3, 250)
colnames(mydata) <- paste0('X', 1:250)
myhux <- as_hux(mydata, add_colnames = TRUE)
myhux <- set_all_borders(myhux, 1)
background_color(myhux)[1,] <- 'grey'
background_color(myhux)[myhux == 'M'] <- 'green'
background_color(myhux)[find_pattern('A.C', myhux)] <- 'yellow'
background_color(myhux)[find_pattern('NF', myhux)] <- 'blue'
myhux
这导致:
find_pattern
函数将接受您向其抛出的任何 perl 正则表达式。 A.C
表示,A,后跟任意字母,再后跟 C。
此查询是对我之前在本论坛中的
任何包含字母的相邻单元格,例如
A?C
,其中?
可以是任何字母或仅
M
在一个单元格中或相邻单元格中的 N 和 F,例如
NF
,如下图所示。
也就是说,需要把这个table转换成
这在 R Shiny DT 中使用 rowCallback 函数。
我在这里拉我的包,所以这对你来说可能不合适,因为它只使用 HTML table 而不是 DT,并且在 R 端工作而不是在 javascript.
find_pattern <- function (pat, mat) {
# collapse the row into a single string:
strings <- apply(mat, 1, paste0, collapse = '')
# find the patterns you want:
found <- gregexpr(pat, strings, perl = TRUE)
# the rest is just housekeeping:
pos <- matrix(FALSE, nrow(mat), ncol(mat))
lapply(seq_along(found), function (x) {
matches <- found[[x]]
lens <- attr(matches, 'match.length')
if (all(matches == -1)) return()
for (p in seq_along(matches)) {
start <- matches[p]
len <- lens[p]
end <- start + len - 1
pos[x, start:end] <<- TRUE
}
})
which(pos, arr.ind = TRUE)
}
library(huxtable)
mydata <- matrix(sample(c('A', 'B', 'C', 'M', 'N', 'F'), 750, replace=TRUE), 3, 250)
colnames(mydata) <- paste0('X', 1:250)
myhux <- as_hux(mydata, add_colnames = TRUE)
myhux <- set_all_borders(myhux, 1)
background_color(myhux)[1,] <- 'grey'
background_color(myhux)[myhux == 'M'] <- 'green'
background_color(myhux)[find_pattern('A.C', myhux)] <- 'yellow'
background_color(myhux)[find_pattern('NF', myhux)] <- 'blue'
myhux
这导致:
find_pattern
函数将接受您向其抛出的任何 perl 正则表达式。 A.C
表示,A,后跟任意字母,再后跟 C。