How to give each instance its own row in a data frame? [duplicate]

强颜欢笑 提交于 2019-12-20 05:02:31

问题


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

回答1:


rep(df$object, df$count)

If you want the 2 columns:

df2 = data.frame(object = rep(df$object, df$count))
df2$count = 1



回答2:


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

library(tidyverse)

uncount(df, count) %>% mutate(observation = 1)



回答3:


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


来源:https://stackoverflow.com/questions/58661167/how-to-give-each-instance-its-own-row-in-a-data-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!