如何为每个product_id生成12个月数据并重复对应coef值?
Expand Product Data to Monthly Records in R
Hey there! Let's figure out how to expand your product data to have 12 monthly records for 2018, keeping each product's coef value consistent across all months. I'll share two straightforward methods to get this done in R:
Using the tidyverse (tidyr)
This is a clean, intuitive approach using the tidyr package (part of the tidyverse):
# Load the required package library(tidyr) # Your original dataset mydat <- structure(list(product_id = 11511:11512, coef = c(1L, 1L)), .Names = c("product_id", "coef"), class = "data.frame", row.names = c(NA, -2L)) # Expand to monthly records expanded_dat <- mydat %>% crossing(months = month.abb) %>% # Uses R's built-in 3-letter month abbreviations arrange(product_id, months) # Optional: sort results by product and month # Preview the first 6 rows head(expanded_dat)
How this works:
crossing()combines every row of your original data with every element in themonthsvector (we usemonth.abbto get Jan-Dec as 3-letter abbreviations automatically).- This method automatically repeats the
coefvalue for every month associated with a product_id.
Base R Approach
If you don't want to use external packages, here's a base R solution:
# Your original dataset mydat <- structure(list(product_id = 11511:11512, coef = c(1L, 1L)), .Names = c("product_id", "coef"), class = "data.frame", row.names = c(NA, -2L)) # Create a vector of month abbreviations months_vec <- month.abb # Generate all product-month combinations product_month_pairs <- expand.grid(product_id = mydat$product_id, months = months_vec) # Merge to add the corresponding coef values expanded_dat <- merge(product_month_pairs, mydat, by = "product_id") # Optional: sort the final dataset expanded_dat <- expanded_dat[order(expanded_dat$product_id, expanded_dat$months), ] # Preview the first 6 rows head(expanded_dat)
How this works:
expand.grid()creates every possible pair ofproduct_idandmonths.- We then merge this with the original data to attach the correct
coefvalue to each product-month pair.
Sample Output
Both methods will produce a dataset that looks like this (showing the first 6 rows):
product_id months coef 1 11511 Jan 1 2 11511 Feb 1 3 11511 Mar 1 4 11511 Apr 1 5 11511 May 1 6 11511 Jun 1
Each product_id will have 12 total records (one for each month), with the coef value unchanged across all months.
内容的提问来源于stack exchange,提问作者psysky
相关产品推荐
相关产品推荐

