【发布时间】:2015-06-29 14:46:03
【问题描述】:
我正在编写一个聚合数据框的函数,它需要普遍适用于各种数据集。此函数的一个步骤是 dplyr 的 filter 函数,用于从数据中仅选择与手头任务相关的广告活动类型。由于我需要灵活的函数,因此我希望将 ad_campaign_types 作为输入,但这使得过滤有点麻烦,如下所示:
aggregate_data <- function(ad_campaign_types) {
raw_data %>%
filter(ad_campaign_type == ad_campaign_types) -> agg_data
agg_data
}
new_data <- aggregate_data(ad_campaign_types = c("campaign_A", "campaign_B", "campaign_C"))
我认为上述方法可行,但在运行时,奇怪的是它只返回过滤数据集应有的一小部分。有没有更好的方法来做到这一点?
另一个可替换代码的小例子:
ad_types <- c("a", "a", "a", "b", "b", "c", "c", "c", "d", "d")
revenue <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
data <- as.data.frame(cbind(ad_types, revenue))
# Now, filtering to select only ad types "a", "b", and "d",
# which should leave us with only 7 values
new_data <- filter(data, ad_types == c("a", "b", "d"))
nrow(new_data)
[1] 3
【问题讨论】: