Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new vector that represents the count

Tags:

r

count

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)
like image 251
JC3019 Avatar asked Jul 27 '19 08:07

JC3019


People also ask

How to count frequency in a vector in R?

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.

How do I count the number of data in R?

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.


2 Answers

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
like image 134
Cole Avatar answered Oct 19 '22 05:10

Cole


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

like image 2
ZiGaelle Avatar answered Oct 19 '22 04:10

ZiGaelle