首页 > 解决方案 > How to remove a column and increase count of rows based on the value of the columns

问题描述

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!!

标签: rdataframe

解决方案


base R一个选项rep

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

-输出

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

推荐阅读