汇总特定的行集

时间:2014-08-24 06:29:08

标签: r

我想总结每个项目的数据(多行),以便删除没有任何类型的促销的项目。请参阅示例数据。

item_code vendor_code launch_month unit_price department_name  category_name
1  I-111164         V10     2007.M01        118            Face Face Treatment
2  I-111164         V10     2007.M01        118            Face Face Treatment
3  I-111164         V10     2007.M01        118            Face Face Treatment
4  I-111164         V10     2007.M01        118            Face Face Treatment
5  I-111164         V10     2007.M01        118            Face Face Treatment
6  I-111164         V10     2007.M01        118            Face Face Treatment
      subcategory_name sales_velocity sales_month sales_unit      promotion_type
1 Face Treatment Other              B    2008.M01   41.00000        no_promotion
2 Face Treatment Other              B    2008.M02   55.00000        no_promotion
3 Face Treatment Other              B    2008.M03   64.80000 Catalogue Promotion
4 Face Treatment Other              B    2008.M04   46.00000        no_promotion
5 Face Treatment Other              B    2008.M05   67.00000        no_promotion
6 Face Treatment Other              B    2008.M06   58.40000 Catalogue Promotion
> 

R 中执行此操作的最佳做​​法是什么?

3 个答案:

答案 0 :(得分:1)

以下命令返回的数据框没有没有任何类型促销的行:

dat[dat$promotion_type != "no_promotion", ]

其中dat是数据框的名称。

答案 1 :(得分:0)

library(dplyr)
item_code <- rep(c("I-111164"), each = 1, times = 6)
vendor_code <- rep(c("V10"), each = 1, times = 6)
launch_month <- rep(c("2007.M01"), each = 1, times = 6)
unite_price <- rep(c("118"), each = 1, times = 6)
department_name <- rep(c("Face"), each = 1, times = 6)
category_name <- rep(c("Face Treatment"), each = 1, times = 6)
subcategory_name <- rep(c("Face Treatment other"), each = 1, times = 6)
sales_velocity <- rep(c("B"), each = 1, times = 6)
sales_month <- rep(c("2008.M01"), each = 1, times = 6)
sales_unit <- rep(c(41,55,64,46,67,58), each = 1, times = 1)
promotion_type <- c("no_promotion", "no_promotion", "catalogue promotion",
                "no_promotion", "no_promotion", "catalogue promotion")

# Create the data frame             
foo <- data.frame(item_code, vendor_code, launch_month, unite_price, department_name,
category_name, subcategory_name, sales_velocity, sales_month,sales_unit, promotion_type,    stringsAsFactors = F)

# Remove all rows with 'no_promotion'
foo2 <- filter(foo, promotion_type != "no_promotion")

# Get mean of sales unit for each item code
america <- foo2 %>%
       group_by(item_code) %>%
       summarize(sales = mean(sales_unit))

america

答案 2 :(得分:0)

首先,您要获取所有促销项目的商品代码。假设您的数据框名为df,请使用

got.promoted <- df$item_code[df$promotion_type != "no_promotion"]

这将是具有正确代码的向量。它可能包含重复项,您可以使用

删除它
got.promoted <- unique(got.promoted)

然后使用此向量从原始数据框中选择获得促销的项目:

new.df <- df[df$item_code %in% got.promoted, ]

我不会声称这是“最佳实践”方式,但它应该有效并且易于理解。