Include Levels of Zero Count in Result of Table()

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

Include levels of zero count in result of wpct() (weighted table of percentages) in R

We could use complete to create a missing observation

library(dplyr)
library(tidyr)
library(weights)
tibble(test, weight) %>%
complete(test = 1:5, fill = list(weight = 0)) %>%
summarise(out = wpct(test, weight))

-output

# A tibble: 5 x 1
out
<dbl>
1 0.212
2 0.182
3 0.364
4 0
5 0.242

Include missing factor levels in xtabs

You need to convert A and B to the factor class and both of them have the same levels 0 and 1.

df[] <- lapply(myDF, factor, levels = c(0, 1))
table(df)

B
A 0 1
0 0 4
1 0 0

Indexing tables of logical vectors with zero counts in R

Convert to factor with levels specified so that it always have two levels - without a TRUE value, there is no way the table to create the count of TRUE as that information is not present. With factor levels, it gives the TRUE count to be 0

table(factor(v2, levels = c(FALSE, TRUE)))[2]

It is not clear why a logical vector TRUE values needs to be counted with table and then extract based on the TRUE, FALSE names. It can be more easily done with sum as TRUE -> 1 and FALSE -> 0, negating (!) reverses this

> sum(v1)
[1] 3
> sum(!v1)
[1] 2
> sum(v2)
[1] 0
> sum(!v2)
[1] 5

Keeping zero count combinations when aggregating with data.table

Seems like the most straightforward approach is to explicitly supply all category combos in a data.table passed to i=, setting by=.EACHI to iterate over them:

setkey(dt, sex, fruit)
dt[CJ(sex, fruit, unique = TRUE), .N, by = .EACHI]
# sex fruit N
# 1: F apple 2
# 2: F orange 0
# 3: F tomato 2
# 4: H apple 3
# 5: H orange 1
# 6: H tomato 1

Display extra values in table function from base R

I find the easiest way to do this is to convert to a factor with the desired levels:

table(df$date, factor(df$value, levels = 1:5))
#>
#> 1 2 3 4 5
#> 2020-08-10 1 0 0 0 0
#> 2020-08-11 1 0 0 0 0
#> 2020-08-12 0 0 1 0 0
#> 2020-08-13 0 0 1 0 0
#> 2020-08-14 0 0 0 0 1
#> 2020-08-15 0 0 0 0 1

Include zero frequencies in frequency table for Likert data

table produces a contingency table, while tabular produces a frequency table that includes zero counts.

tabulate(data)
# [1] 3 1 0 2 1

Another way (if you have integers starting from 1 - but easily modifiable for other cases):

setNames(tabulate(data), 1:max(data))  # to make the output easier to read
# 1 2 3 4 5
# 3 1 0 2 1


Related Topics



Leave a reply



Submit