0

Give a dataframe in R

structure(list(Feat1 = c("A", "B", "A", "B"), Time = c("Start", 
"Start", "Finish", "Finish"), Value = c("Value1", "Value2", "Value3", 
"Value2"), feat2 = c("Alpha", "Bravo", "Alpha", "Bravo"), Frequency = c(2L, 
4L, 5L, 3L)), class = "data.frame", row.names = c(NA, -4L))

I have both the frequencies and also features of a certain set of observations. I want all the frequencies to be converted to a number of rows equal to the frequency value while keeping the features.

As an example, the first row becomes these 2 rows because frequency was 2 enter image description here

Maël
  • 45,206
  • 3
  • 29
  • 67
rj44
  • 165
  • 7

2 Answers2

3

Try uncount:

library(tidyr)
dat %>% 
  uncount(Frequency)

output:

   Feat1   Time  Value feat2
1      A  Start Value1 Alpha
2      A  Start Value1 Alpha
3      B  Start Value2 Bravo
4      B  Start Value2 Bravo
5      B  Start Value2 Bravo
6      B  Start Value2 Bravo
7      A Finish Value3 Alpha
8      A Finish Value3 Alpha
9      A Finish Value3 Alpha
10     A Finish Value3 Alpha
11     A Finish Value3 Alpha
12     B Finish Value2 Bravo
13     B Finish Value2 Bravo
14     B Finish Value2 Bravo
Maël
  • 45,206
  • 3
  • 29
  • 67
  • 1
    not my downvote but it does get a little bit tiresome seeing some high rep users (not you!) repeatedly answer very obvious dupes over and over again. – user438383 Aug 10 '22 at 16:19
0

A base solution:

df[rep(seq_len(nrow(df)), df$Frequency), ]

where the rep part gives a repeated indices fro each row.

[1] 1 1 2 2 2 2 3 3 3 3 3 4 4 4
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51