I want to create a vector of counts in the following way:
say my vector is
x <- c(1,1,1,1,2)
which represents a categorical variable. I want a second vector of the form
x1 <- c(4,4,4,4,1)
which represents the count at each level. e.g. 4 occurrences of level 1, and 1 occurrence of level 2.
I have tried
r <- range(x) ; table(factor(x, levels = r[1]:r[2]))
tabulate(factor(x, levels = min(x):max(x)))
table(x)
There are multiple ways to get the count of the frequency of all unique values in an R vector. To count the number of times each element or value is present in a vector use either table(), tabulate(), count() from plyr package, or aggregate() function.
The ncol() function in R programming R programming helps us with ncol() function by which we can get the information on the count of the columns of the object. That is, ncol() function returns the total number of columns present in the object.
This uses ave
to group by each value. This would likely be better if your vector is definitely an integer
type.
x <- c(1,1,1,1,2)
ave(x, x, FUN = length)
[1] 4 4 4 4 1
Equivalents in data.table
and dplyr
:
library(data.table)
data.table(x)[, n:= .N, by = 'x'][]
x n
1: 1 4
2: 1 4
3: 1 4
4: 1 4
5: 2 1
library(dplyr)
library(tibble)
tibble::enframe(x, name = NULL)%>%
add_count(value)
##or
x%>%
tibble::enframe(name = NULL)%>%
group_by(value)%>%
mutate(n = n())%>%
ungroup()
# A tibble: 5 x 2
value n
<dbl> <int>
1 1 4
2 1 4
3 1 4
4 1 4
5 2 1
If you do it like this:
x = c(1,1,1,1,2)
x1 = as.vector(table(x)[x])
You obtain the vector you wanted:
[1] 4 4 4 4 1
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