Ignacio Ignacio - 1 year ago 62
R Question

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

df1 <-
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
to hide the columns that only have zeros? In this case
, and

I can do this:

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 Source

If df1 is a data.frame you could do:

df1[, colSums(df1 != 0) > 0]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download