Lucas
Lucas

Reputation: 589

create a list subsetting data frame and join other list based on previous in r

I have time series for each product:

ts <- list()
ts[["p1"]] <- ts(seq(1,5), start=c(2019,1), frequency=12)
ts[["p2"]] <- ts(seq(1,5), start=c(2019,1), frequency=12)
ts[["p3"]] <- ts(seq(1,5), start=c(2019,1), frequency=12)
ts[["p4"]] <- ts(seq(1,5), start=c(2019,1), frequency=12)
ts[["p5"]] <- ts(seq(1,5), start=c(2019,1), frequency=12)

and a relationship between product and category in a data frame

category <- c("cA","cA","cB","cB","cB")
product <- c("p1","p2","p3","p4","p5")
df_product_category <- data.frame(product,category)

I first want a list for each category:

list_category <- list(unique(df_product_category$category))
#this doesn´t work

Then I want to create another list per category containing all the products within the category

list_category <- c("cA","cB")

once I have this list I need a nested list for each category containing each of the products within that category

list_product_category <- list()
list_product_category$'cA' <- c("p1","p2")
list_product_category$'cB' <- c("p2","p3","p4")

then I wish to create another list nesting: category-product-tslike this:

ts_list_product_category <- list()
ts_list_product_category[[cA]]$p1 <- ts[["p1"]]
ts_list_product_category[[cA]]$p2 <- ts[["p2"]]
ts_list_product_category[[cB]]$p3 <- ts[["p3"]]
ts_list_product_category[[cB]]$p4 <- ts[["p4"]]
ts_list_product_category[[cB]]$p5 <- ts[["p5"]]

Thanks in advance :)

Upvotes: 0

Views: 43

Answers (2)

akrun
akrun

Reputation: 887118

We can do a split to create the 'list_product_category'. Once we have that it is easier to create the 'ts_list_product_category', by just subsetting using the values as names for the 'ts'

list_product_category <- with(df_product_category,    
          split(as.character(product), category))

out <-  lapply(list_product_category, function(x) ts[x])

-checking with OP's created output

identical(out, ts_list_product_category )
#[1] TRUE

Upvotes: 1

Neel Kamal
Neel Kamal

Reputation: 1076

Try this... A robust approach.

library(tidyverse)

(d <- df_product_category %>% group_by(category) %>% nest()) %>% glimpse()

output dataset structure

Observations: 2
Variables: 2
Groups: category [2]
$ category <fct> cA, cB
$ data     <list> [<tbl_df[2 x 1]>, <tbl_df[3 x 1]>]

Upvotes: 1

Related Questions