R Table Function - How to Remove 0 Counts

R table function - how to remove 0 counts?

you need to drop levels from the factor animal.

table(droplevels(ds$animal),ds$gender)

you can also just drop them from ds and then do the table

ds$animal <- droplevels(ds$animal)
with(ds, table(animal,gender))

here I used with because it prints headers.

aggregate in r is removing 0 count in table. How to make it show?

We need to create the 'var' as factor with levels specified as 0 and 1. This would make sure that if the count is 0 for a particular column to show up as 0

var <- factor(var, levels = 0:1)
out <- aggregate(var, list(group), FUN = table)
out
# Group.1 x.0 x.1
#1 1 29 21
#2 2 29 21
#3 3 23 27
#4 4 0 50

Or use the formula method

out <- aggregate(var ~ group, FUN = table)

Note that these will result in a matrix 'x' with two columns. Inorder to have as regular data.frame columns

do.call(data.frame, out)

Or in case, for a change, we can also get the sum of 1s and then reshape

reshape(aggregate(cbind(n = rep(1, length(group))) ~ 
group+ var, FUN = sum), idvar = 'group', direction = 'wide', timevar = 'var')

If we are using tidyverse, instead of doing any change in the class i.e. converting to factor, do a count using both the variables and then spread it to 'wide' format

library(tidyverse)
tibble(var, group) %>%
count(var, group) %>%
spread(var, n, fill = 0)
# A tibble: 4 x 3
# group `0` `1`
# <int> <dbl> <dbl>
#1 1 29 21
#2 2 29 21
#3 3 23 27
#4 4 0 50

data

set.seed(24)
var <- sample(0:1, 200, replace = TRUE)
var[151:200] <- 1
group <- rep(1:4, each = 50)

Include levels of zero count in result of table()

Convert your variable to a factor, and set the categories you wish to include in the result using levels. Values with a count of zero will then also appear in the result:

y <- c(0, 0, 1, 3, 4, 4)
table(factor(y, levels = 0:5))
# 0 1 2 3 4 5
# 2 1 0 1 2 0

How to remove rows with any zero value

There are a few different ways of doing this. I prefer using apply, since it's easily extendable:

##Generate some data
dd = data.frame(a = 1:4, b= 1:0, c=0:3)

##Go through each row and determine if a value is zero
row_sub = apply(dd, 1, function(row) all(row !=0 ))
##Subset as usual
dd[row_sub,]

Getting table() to return zeroes in R

I haven't tested this, but I believe you want

table(factor(x, levels = 0:14))

Remove columns with zero values from a dataframe

You almost have it. Put those two together:

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

This works because the factor columns are evaluated as numerics that are >= 1.

How to delete R data.frame columns with only zero values?

One option using dplyr could be:

df %>%
select(where(~ any(. != 0)))

1 0 2 2
2 2 3 5
3 5 0 1
4 7 0 2
5 2 1 3
6 3 0 4
7 0 4 5
8 3 0 6


Related Topics



Leave a reply



Submit