Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

dplyr - How do I loop over a list to create a new ID based on list values in R?

I have the following data:

| parent_sku |  stock_status | regular_price | tax_class | 
|:----------:|:-------------:|:-------------:|:---------:|
| ABBBOA01   |  instock      | 1299          | parent    | 
| ABBBOA03   |  instock      | 1299          | parent    | 
| ABBBOA02   |  instock      | 1299          | parent    | 
| ABBBOA04   |  instock      | 1299          | parent    | 

I would like to generate four new sku for each parent_sku, M,L, XL and XXL. For example, the above data should be transformed to:

| parent_sku |    sku      | stock_status | regular_price | tax_class |    attribute_size   |
|:----------:|:-----------:|:------------:|:-------------:|:---------:|:-------------------:|
| ABBBOA01   | ABBBOA01M   | instock      | 1299          | parent    | M                   |
| ABBBOA01   | ABBBOA01L   | instock      | 1299          | parent    | L                   |
| ABBBOA01   | ABBBOA01X   | instock      | 1299          | parent    | XL                  |
| ABBBOA01   | ABBBOA01XXL | instock      | 1299          | parent    | XXL                 |
| ABBBOA03   | ABBBOA03M   | instock      | 1299          | parent    | M                   |
| ABBBOA03   | ABBBOA03L   | instock      | 1299          | parent    | L                   |
| ABBBOA03   | ABBBOA03XL  | instock      | 1299          | parent    | XL                  |
...
and so on

Basically, append the attribute_size to the parent_sku for each entry.

Based on this answer, I've tried doing this:

sizes <- c("M", "L", "XL", "XXL")

data <- data %>% mutate(attribute_size = list(sizes)) %>%
  unnest_longer(attribute_size)
data <- data %>% 
      mutate(sku = paste0(parent_sku, list(sizes))) 

But this just adds ABBBOA01c("M", "L", "XL", "XXL") to the sku column. How do I loop over the sizes? I think this is one of those situations which requires lapply but I'm not sure.

question from:https://stackoverflow.com/questions/65940434/how-do-i-loop-over-a-list-to-create-a-new-id-based-on-list-values-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...