Add missing columns to an R table
r
Solution
Use a factor:
table(factor(y, levels = names(x)))
# A B C D E F G H I J K L
# 2 0 1 0 4 2 0 0 0 1 1 2
Problem
Given this sample data: ``` x = 1:12; names(x) = LETTERS[1:length(x)] y = c('A','C','E','F','J','E','K','L','E','L','F','A','E') ``` When I do `table(y)` I get: ``` A C E F J K L 2 1 4 2 1 1 2 ``` How do I expand that to include zero entries for all the other column headings in `x`? In other words the output I'm after is: ``` A C E F J K L B D G H I 2 1 4 2 1 1 2 0 0 0 0 0 ``` (unsorted as shown there, or sorted, I don't mind.)