1

How is it possible to transform this data frame so that the count is divided into separate observations?

df = data.frame(object = c("A","B", "A", "C"), count=c(1,2,3,2))

  object count
1      A     1
2      B     2
3      A     3
4      C     2

So that the resulting data frame looks like this?

  object observation
1      A           1
2      B           1
3      B           1
4      A           1
5      A           1
6      A           1
7      C           1
8      C           1
Z.Lin
  • 28,055
  • 6
  • 54
  • 94
Gilgafresh
  • 11
  • 1

3 Answers3

2
rep(df$object, df$count)

If you want the 2 columns:

df2 = data.frame(object = rep(df$object, df$count))
df2$count = 1
glagla
  • 611
  • 4
  • 9
1

If you're working with tidyverse - otherwise that's overkill -, you could also do:

library(tidyverse)

uncount(df, count) %>% mutate(observation = 1)
arg0naut91
  • 14,574
  • 2
  • 17
  • 38
1

Using data.table:

library(data.table)
setDF(df)[rep(seq_along(count), count), .(object, count = 1L)]

   object count
1:      A     1
2:      B     1
3:      B     1
4:      A     1
5:      A     1
6:      A     1
7:      C     1
8:      C     1
s_baldur
  • 29,441
  • 4
  • 36
  • 69