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.)
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
I can't think of a way to do this with table, but it's a pretty simple one-liner regardless:
sapply(names(x), function(name) {sum(y == name)})
Output:
A B C D E F G H I J K L
2 0 1 0 4 2 0 0 0 1 1 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With