【发布时间】:2020-07-03 06:45:13
【问题描述】:
我想添加一个新列SubCategory,其值根据Category 列的值随机填充。详情如下:
Sub_Hair = c("Shampoo", "Conditioner", "Gel", "HairOil", "Dye")
Sub_Beauty = c("Face", "Eye", "Lips")
Sub_Nail= c("NailPolish", "NailPolishRemover", "NailArtKit", "ManiPadiKit")
Sub_Others = c("Electric", "NonElectric")
> product_data_1[1:10, c("Pcode", "Category", "MRP")]
Pcode Category MRP
1 16156L Beauty $8.88
2 16162M Others $21.27
3 16168M Others $2.98
4 16169E Nail $26.64
5 16207A Hair $6.38
6 17012B Beauty $33.03
7 17012C Beauty $20.58
8 17012F Beauty $36.29
9 17091A Nail $20.55
10 17107D Nail $28.20
我正在尝试下面的代码。但是,行正在更新,每个类别只有一个子类别。例如,所有具有“美容”类别的行,子类别都是“眼睛”,而不是从“面部、眼睛和嘴唇”中随机选择的值。这是代码和输出:
product_data_1 = within(product_data_1, SubCategory[Category == "Beauty"] <- sample(Sub_Beauty, 1))
product_data_1 = within(product_data_1, SubCategory[Category == "Hair"] <- sample(Sub_Hair, 1))
product_data_1 = within(product_data_1, SubCategory[Category == "Nail"] <- sample(Sub_Nail, 1))
product_data_1 = within(product_data_1, SubCategory[Category == "Others"] <- sample(Sub_Others, 1))
> product_data_1[1:10, c("Pcode", "Category", "MRP", "SubCategory")]
Pcode Category MRP SubCategory
1 16156L Beauty $8.88 Eye
2 16162M Others $21.27 Electric
3 16168M Others $2.98 Electric
4 16169E Nail $26.64 NailPolish
5 16207A Hair $6.38 Gel
6 17012B Beauty $33.03 Eye
7 17012C Beauty $20.58 Eye
8 17012F Beauty $36.29 Eye
9 17091A Nail $20.55 NailPolish
10 17107D Nail $28.20 NailPolish
【问题讨论】:
标签: r replace conditional-statements