Darren Cook
Darren Cook

Reputation: 28913

Add missing columns to an R table

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.)

Upvotes: 2

Views: 616

Answers (2)

flodel
flodel

Reputation: 89057

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 

Upvotes: 10

Marius
Marius

Reputation: 60060

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 

Upvotes: 5

Related Questions