Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new rows based on numbers in a column [duplicate]

Tags:

r

I currently have a table with a quantity in it.

ID Code Quantity
1 A 1
2 B 3
3 C 2
4 D 1

Is there anyway to get this table?

ID Code Quantity
1 A 1
2 B 1
2 B 1
2 B 1
3 C 1
3 C 1
4 D 1

I need to break out the quantity and have that many number of rows.

Thanks!!!!

like image 718
Laura Cuesta Avatar asked Oct 31 '25 20:10

Laura Cuesta


2 Answers

Updated Now we have stored the separated, collapsed values into a new column:

library(dplyr)
library(tidyr)

df %>%
  group_by(ID) %>%
  uncount(Quantity, .remove = FALSE) %>%
  mutate(NewQ = 1)

# A tibble: 7 x 4
# Groups:   ID [4]
     ID Code  Quantity  NewQ
  <int> <chr>    <int> <dbl>
1     1 A            1     1
2     2 B            3     1
3     2 B            3     1
4     2 B            3     1
5     3 C            2     1
6     3 C            2     1
7     4 D            1     1

Updated In case we opt not to replace the existing Quantity column with the collapsed values.

df %>%
  group_by(ID) %>%
  mutate(NewQ = ifelse(Quantity != 1, paste(rep(1, Quantity), collapse = ", "),
                           as.character(Quantity))) %>%
  separate_rows(NewQ) %>%
  mutate(NewQ = as.numeric(NewQ))


# A tibble: 7 x 4
# Groups:   ID [4]
     ID Code  Quantity  NewQ
  <int> <chr>    <int> <dbl>
1     1 A            1     1
2     2 B            3     1
3     2 B            3     1
4     2 B            3     1
5     3 C            2     1
6     3 C            2     1
7     4 D            1     1
like image 177
Anoushiravan R Avatar answered Nov 03 '25 10:11

Anoushiravan R


We could use slice

library(dplyr)
df %>% 
  group_by(ID) %>% 
  slice(rep(1:n(), each = Quantity)) %>% 
  mutate(Quantity= rep(1))

Output:

     ID Code  Quantity
  <dbl> <chr>    <dbl>
1     1 A            1
2     2 B            1
3     2 B            1
4     2 B            1
5     3 C            1
6     3 C            1
7     4 D            1
like image 30
TarJae Avatar answered Nov 03 '25 11:11

TarJae