Creating new vector that represents the count

JC3*_*019 6 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)
Run Code Online (Sandbox Code Playgroud)

which represents a categorical variable. I want a second vector of the form

x1 <- c(4,4,4,4,1)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

Col*_*ole 6

这用于ave对每个值进行分组。如果您的向量绝对是integer类型,则可能会更好。

x <- c(1,1,1,1,2)

ave(x, x,  FUN = length)
[1] 4 4 4 4 1
Run Code Online (Sandbox Code Playgroud)

data.table和中的等效项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
Run Code Online (Sandbox Code Playgroud)