1

I'm relatively new to R. I have a data frame with 939 rows that looks like this:

cuisine Number.of.order Customer_id
Fastfood 2 1
cakes 3 1
Western 4 2
Chinese 5 3

What i want is to get rid of the Numbers.of.order column and add the values inside the column as addition rows.

Something like this:

cuisine Customer_id
Fastfood 1
Fastfood 1
cakes 1
cakes 1
cakes 1
Western 2
Western 2
Western 2
Western 2
Chinese 3
Chinese 3
Chinese 3
Chinese 3
Chinese 3

Im doing this so that I can convert it into a transaction dataframe for association rules.

Any help would be greatly appreciated!!

Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
Abraham
  • 111
  • 1

2 Answers2

2

You can use the following solution:

library(dplyr)

df %>%
    uncount(Number.of.order)

    cuisine Customer_id
1  Fastfood           1
2  Fastfood           1
3     cakes           1
4     cakes           1
5     cakes           1
6   Western           2
7   Western           2
8   Western           2
9   Western           2
10  Chinese           3
11  Chinese           3
12  Chinese           3
13  Chinese           3
14  Chinese           3
Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
2

An option in base R with rep

out <- df1[rep(seq_len(nrow(df1)), df1$Number.of.order), -2]
row.names(out) <- NULL

-output

out
    cuisine Customer_id
1  Fastfood           1
2  Fastfood           1
3     cakes           1
4     cakes           1
5     cakes           1
6   Western           2
7   Western           2
8   Western           2
9   Western           2
10  Chinese           3
11  Chinese           3
12  Chinese           3
13  Chinese           3
14  Chinese           3
akrun
  • 874,273
  • 37
  • 540
  • 662