using tally to filter data in R

119 Views Asked by At

i have generated a contingency table using tally(), however there is some invalid data:

structure(c(0L, 5L, 0L, 1L, 2L, 4L, 3L, 2L, 0L, 3L, 11L, 7L, 
3L, 6L, 3L, 26L, 27L, 16L, 5L, 4L, 69L, 78L, 36L, 19L, 12L, 88L, 
133L, 70L, 29L, 25L, 84L, 132L, 58L, 24L, 23L, 44L, 52L, 25L, 
16L, 3L), .Dim = c(5L, 8L), .Dimnames = list(D5 = c("1", "2", 
"3", "4", NA), X4.1 = c("-9", "1", "2", "3", "4", "5", "6", "7"
)), class = "table")

I need to remove the rows & columns of such - i need to remove the first column and the last row. I have tried using the %>% operator, but keep getting errors.

Any tips?

1

There are 1 best solutions below

0
On

It is a table object and not a data.frame.

> str(df1)
 'table' int [1:5, 1:8] 0 5 0 1 2 4 3 2 0 3 ...
 - attr(*, "dimnames")=List of 2
  ..$ D5  : chr [1:5] "1" "2" "3" "4" ...
  ..$ X4.1: chr [1:8] "-9" "1" "2" "3" ...

So we can use indexing to do the removal - nrow(df1) returns the number of rows, use this as row index with - to remove the last row and -1 as column index to remove the first column

df2 <- df1[-nrow(df1), -1]
df2
 X4.1
D5    1   2   3   4   5   6   7
  1   4  11  26  69  88  84  44
  2   3   7  27  78 133 132  52
  3   2   3  16  36  70  58  25
  4   0   6   5  19  29  24  16