Reputation: 111
I have this piece of code that I can run against one data frame. However, I'd like to be able to loop it over a data frame list.
This is the base code:
# Run RFM Analysis on df_0
df_1 <- rfm_table_order(df_0, customer = customer_id, order_date = txn_date, revenue = txn_price, analysis_date = analysis_date,
recency_bins=3, frequency_bins=3, monetary_bins=3)
df_2 <- as.data.frame(df_1$rfm)
# Add weighting to the scores
df_2$finalscore <- (df_2 $recency_score*3 + df_2 $frequency_score*2 + df_2 $monetary_score*3)/8
# Add labels according to weighted score
df_2<- df_2 %>%
mutate(segment = case_when(
.$finalscore >= 2.5 ~ "Loyal",
.$finalscore <= 1.5 ~ "Lapsed",
TRUE ~ "Regular"
))
# Add the analysis date
df_2$analysis_date <- rep(analysis_date,nrow(df_2))
# Output the final dataset with required rows
df_final <- df_2[,c("customer_id","segment","analysis_date")]
df_0 looks like this:
customer_id txn_date txn_price category
123 01/01/2019 12 a
456 01/02/2019 7 b
...
After running the above code, df_final looks like this:
customer_id segment analysis_date
123 Loyals 01/05/2019
456 Loyals 01/05/2019
...
I wanted to see how the results would differ if I use category as a factor. Because of that, I made a data frame list.
cat_list <- split(df_0, as.factor(df_0$category))
I need to add a loop that runs against a dataframe list. The last step in the loop should also append the name of the data frame into the result.
Desired output:
customer_id segment category analysis_date
123 Loyals a 01/05/2019
456 Loyals b 01/05/2019
...
Upvotes: 1
Views: 87
Reputation: 107652
Simply generalize your process that takes a data frame as input and run by
(roughly equivalent to split
+ lapply
) to subset main data frame by category and pass subsets into function. Consider also within
and ifelse
for adding needed columns (base R or tinyverse version of mutate
and case_when
)
Function
my_func <- function(sub_df) {
# Run RFM Analysis on df
df_1 <- rfm_table_order(sub_df, customer = customer_id, order_date = txn_date,
revenue = txn_price, analysis_date = analysis_date,
recency_bins=3, frequency_bins=3, monetary_bins=3)
df_2 <- within(as.data.frame(df_1$rfm), {
# Add weighting to the scores
finalscore <- (recency_score*3 + frequency_score*2 + monetary_score*3)/8
# Add labels according to weighted score
segment <- ifelse(finalscore >= 2.5, "Loyal",
ifelse(finalscore <= 1.5, "Lapsed", "Regular")
)
# Add the analysis date
analysis_date <- analysis_date
# Add category
category <- sub_df$category[[1]]
})
# Output the final dataset with required rows
df_final <- df_2[,c("customer_id", "segment", "category", "analysis_date")]
return(df_final)
}
Call
cat_list <- by(df_0, df_0$category, my_func)
# cat_list <- lapply(split(df_0, df_0$category), my_func)
Upvotes: 3