如何编写R代码从产品销量数据集中找出最畅销产品?
Absolutely! You can easily verify your intuition with R using either the tidyverse (dplyr) for readable, pipe-based code or base R if you prefer avoiding extra packages. Here's how:
Step 1: Create the Dataset
First, let's recreate your sales data as a data frame:
sales_data <- data.frame( Products = c( "Laminated", "Laminated", "Laminated", "Laminated", "SUPERSTAR", "TAMAX", "TAMAX", "TAMAX", "GreenDragon", "GreenDragon", "XPLODE", "XPLODE", "EXPERT", "KHANJARBIOSL" ), Quantity = c(520, 150, 639, 702, 3, 500, 20, 40, 40, 50, 40, 20, 40, 40) )
Step 2: Calculate Total Sales with dplyr (Recommended)
The dplyr package makes grouping and summarizing data intuitive. If you haven't installed it yet, run install.packages("dplyr") first.
library(dplyr) # Compute total quantity per product and sort from highest to lowest total_sales <- sales_data %>% group_by(Products) %>% summarise(Total_Quantity = sum(Quantity)) %>% arrange(desc(Total_Quantity)) # Print the full breakdown print(total_sales) # Extract the top-selling product top_seller <- total_sales %>% slice(1) cat("\nTop-selling product:", top_seller$Products, "with total sales of", top_seller$Total_Quantity, "\n")
Step 3: Base R Alternative
If you don't want to use external packages, here's how to do it with base R functions:
# Aggregate total quantity per product total_sales_base <- aggregate(Quantity ~ Products, data = sales_data, sum) # Sort by total quantity (descending) total_sales_base <- total_sales_base[order(-total_sales_base$Quantity), ] # Print results print(total_sales_base) # Get top seller top_seller_base <- total_sales_base[1, ] cat("\nTop-selling product:", top_seller_base$Products, "with total sales of", top_seller_base$Quantity, "\n")
Output Explanation
Both methods will show that Laminated has a total sales volume of 2011 (520+150+639+702), which is significantly higher than the next closest product (TAMAX with 560). This confirms your initial intuition!
内容的提问来源于stack exchange,提问作者Adarsh

