Ignacio Ignacio - 7 days ago 6
R Question

Hide columns where all values are 0 with DT::datatable

df1 <-
structure(
list(
Z = structure(
1:5, .Label = c("A", "B", "C", "D",
"E"), class = "factor"
), H1 = c(0L, 0L, 0L, 0L, 0L), X1 = c(178L,
182L, 197L, 177L, 163L), H2 = c(0L, 0L, 0L, 0L, 0L), X2 = c(85L,
77L, 66L, 68L, 86L), X3 = c(320L, 344L, 332L, 311L, 322L)
), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA,-5L), .Names = c("Z",
"H1", "X1", "H2", "X2", "X3")
)


Is there a way to tell
DT::datable
to hide the columns that only have zeros? In this case
H1
, and
H2


I can do this:

library(DT)
df1 %>%
datatable(rownames = F,
extensions = 'ColVis', options = list(
dom = 'C<"clear">lfrtip',
colVis = list(exclude = c(0), activate = 'mouseover')
))


and then manually hide those columns.

Answer

If df1 is a data.frame you could do:

df1[, colSums(df1 != 0) > 0]