如何在 r 中使用 tidyverse 管道运算符复制相同的表达式?
How to replicate the same expression with tidyverse pipe operator in r?
我想使用 DT::datatble
在数据的每一列中突出显示相应的值。
例如:
library(tidyverse)
data(mtcars)
mtcars <- mtcars %>% mutate(across(everything(), as.character))
datatable(mtcars[, c("vs", "am")]) %>%
formatStyle("vs", backgroundColor = styleEqual(rep(0, sum(mtcars$vs == 0)), rep("yellow", sum(mtcars$vs == 0)))) %>%
formatStyle("am", backgroundColor = styleEqual(rep(1, sum(mtcars$am == 1)), rep("yellow", sum(mtcars$am == 1))))
在实际情况下,我有多个列,我想遍历所有列以添加 formatStyle
。有没有办法在循环中复制 %>% formatstyle()
:
# something to start
l <- list()
l[["vs"]] <- 0
l[["am"]] <- 1
datatable(mtcars[, c("vs", "am")]) %>%
lapply(l, function(i) {
i ... # multiple formatStyle()
})
每列迭代的目的不是为了在vs
中突出显示1
,或者在am
中突出显示0
。
谢谢!
一个选项是执行 for
循环并更新
library(dplyr)
library(DT)
mtcars <- mtcars %>%
mutate(across(everything(), as.character))
dt1 <- datatable(mtcars %>%
select(vs, am))
nm1 <- list(vs = 0, am = 1)
for(i in seq_along(nm1)) {
dt1 <- dt1 %>%
formatStyle(names(nm1)[i], backgroundColor = styleEqual(rep(nm1[[i]],
sum(mtcars$vs == nm1[[i]])), rep("yellow", sum(mtcars$vs == nm1[[i]]))))
}
dt1
-输出
我想使用 DT::datatble
在数据的每一列中突出显示相应的值。
例如:
library(tidyverse)
data(mtcars)
mtcars <- mtcars %>% mutate(across(everything(), as.character))
datatable(mtcars[, c("vs", "am")]) %>%
formatStyle("vs", backgroundColor = styleEqual(rep(0, sum(mtcars$vs == 0)), rep("yellow", sum(mtcars$vs == 0)))) %>%
formatStyle("am", backgroundColor = styleEqual(rep(1, sum(mtcars$am == 1)), rep("yellow", sum(mtcars$am == 1))))
在实际情况下,我有多个列,我想遍历所有列以添加 formatStyle
。有没有办法在循环中复制 %>% formatstyle()
:
# something to start
l <- list()
l[["vs"]] <- 0
l[["am"]] <- 1
datatable(mtcars[, c("vs", "am")]) %>%
lapply(l, function(i) {
i ... # multiple formatStyle()
})
每列迭代的目的不是为了在vs
中突出显示1
,或者在am
中突出显示0
。
谢谢!
一个选项是执行 for
循环并更新
library(dplyr)
library(DT)
mtcars <- mtcars %>%
mutate(across(everything(), as.character))
dt1 <- datatable(mtcars %>%
select(vs, am))
nm1 <- list(vs = 0, am = 1)
for(i in seq_along(nm1)) {
dt1 <- dt1 %>%
formatStyle(names(nm1)[i], backgroundColor = styleEqual(rep(nm1[[i]],
sum(mtcars$vs == nm1[[i]])), rep("yellow", sum(mtcars$vs == nm1[[i]]))))
}
dt1
-输出