How can I split rows up by the number of times located in a column in R?

5

For example, suppose you have the following dataframe:

ID<-c("11", "12", "13", "14", "14")
Date<-c("2020-01-01", "2020-02-01", "2020-03-15", "2020-04-10", "2020-06-01")
Item<-c("Item1", "Item1", "Item2", "Item2", "Item2")
ItemPrice<-c(5, 5, 7, 7, 7)
Quantity<-c(1, 2, -2, 2, 3)
Cost<-c(5, 10, -14, 14, 21)
df<-data.frame(ID, Date, Item, ItemPrice, Quantity, Cost)
df

  ID       Date  Item ItemPrice Quantity Cost
1 11 2020-01-01 Item1         5        1    5
2 12 2020-02-01 Item1         5        2   10
3 13 2020-03-15 Item2         7       -2  -14
4 14 2020-04-10 Item2         7        2   14
5 14 2020-06-01 Item2         7        3   21

However, you wanted to separate the rows by Quantity so each one represents an individual sale like the following:

   ID       Date  Item ItemPrice Quantity Cost
1  11 2020-01-01 Item1         5        1    5
2  12 2020-02-01 Item1         5        1    5
3  12 2020-02-01 Item1         5        1    5
4  13 2020-03-15 Item2         7       -1   -7
5  13 2020-03-15 Item2         7       -1   -7
6  14 2020-04-10 Item2         7        1    7
7  14 2020-04-10 Item2         7        1    7
8  14 2020-06-01 Item2         7        1    7
9  14 2020-06-01 Item2         7        1    7
10 14 2020-06-01 Item2         7        1    7

How could this be achieved?

Share
Improve this question

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue