Creating new vector that represents the count

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

Tags:

R

Count