Reputation: 93
I wanted to create a vector of counts if possible. For example: I have a vector
x <- c(3, 0, 2, 0, 0)
How can I create a frequency vector for all integers between 0 and 3? Ideally I wanted to get a vector like this:
> 3 0 1 1
which gives me the counts of 0, 1, 2, and 3 respectively.
Much appreciated!
Upvotes: 1
Views: 1499
Reputation: 12599
You can just use table():
a <- table(x)
a
x
#0 2 3
#3 1 1
Then you can subset it:
a[names(a)==0]
#0
#3
Or convert it into a data.frame
if you're more comfortable working with that:
u<-as.data.frame(table(x))
u
# x Freq
#1 0 3
#2 2 1
#3 3 1
Edit 1: For levels:
a<- as.data.frame(table(factor(x, levels=0:3)))
Upvotes: 2
Reputation: 73265
You can do
table(factor(x, levels=0:3))
Simply using table(x)
is not enough.
Or with tabulate
which is faster
tabulate(factor(x, levels = min(x):max(x)))
Upvotes: 4
Reputation: 3905
You can do this using rle
(I made this in minutes, so sorry if it's not optimized enough).
x = c(3, 0, 2, 0, 0)
r = rle(x)
f = function(x) sum(r$lengths[r$values == x])
s = sapply(FUN = f, X = as.list(0:3))
data.frame(x = 0:3, freq = s)
#> data.frame(x = 0:3, freq = s)
# x freq
#1 0 3
#2 1 0
#3 2 1
#4 3 1
Upvotes: 2