Setting
My task looks similar to this one but not quite. Suppose I have a symmetric data frame looking like this
df <- data.frame(
matrix(c(1, 7, 0, 5, 9, 0,
7, 4, 0, 8, 2, 0,
0, 0, 0, 0, 0, 0,
5, 8, 0, 1, 1, 0,
9, 2, 0, 1, 1, 0,
0, 0, 0, 0, 0, 0), nrow=6, ncol=6)
)
It looks like this
X1 X2 X3 X4 X5 X6
1 1 7 0 5 9 0
2 7 4 0 8 2 0
3 0 0 0 0 0 0
4 5 8 0 1 1 0
5 9 2 0 1 1 0
6 0 0 0 0 0 0
Because it's symmetric if a row is full of zeros, the corresponding column with the same index will also be full of zeros.
What I want to do
I want to drop all the rows and the columns that contain only zero (in general, I would like to drop all the rows and columns satisfying some condition). Ideally, I would like to use functions within the tidyverse. Would be great if I could use pipes somehow.
Is it possible to do this with pipes?
Important
I made a mistake, I think it's essential that the solution works for sparse matrices. Would it please be possible to have an implementation that works for dgCMatrix
class? I.e. for sparse matrices?
When I try many of the tidyverse implementations below I get
Error in UseMethod("tbl_vars") :
no applicable method for 'tbl_vars' applied to an object of class "c('dgCMatrix', 'CsparseMatrix', 'dsparseMatrix', 'generalMatrix', 'dCsparseMatrix', 'dMatrix', 'sparseMatrix', 'compMatrix', 'Matrix', 'xMatrix', 'mMatrix', 'Mnumeric', 'replValueSp')"