我发现dplyr快速,简单地汇总和汇总数据。但是我找不到使用dplyr解决以下问题的方法。
给出以下数据帧:
df_2017 <- data.frame(expand.grid(1:195,1:65,1:39),
value = sample(1:1000000,(195*65*39)),
period = rep("2017",(195*65*39)),
stringsAsFactors = F)
df_2017 <- df_2017[sample(1:(195*65*39),450000),]
names(df_2017) <- c("company", "product", "acc_concept", "value", "period")
df_2017$company <- as.character(df_2017$company)
df_2017$product <- as.character(df_2017$product)
df_2017$acc_concept <- as.character(df_2017$acc_concept)
df_2017$value <- as.numeric(df_2017$value)
ratio_df <- data.frame(concept=c("numerator","numerator","numerator","denom", "denom", "denom","name"),
ratio1=c("1","","","4","","","Sales over Assets"),
ratio2=c("1","","","5","6","","Sales over Expenses A + B"), stringsAsFactors = F)
df_2017中的列为:
expand.grid暗示,公司-产品-acc_concept 的组合永远不会重复,但是,可能会发生某些主题没有每个公司-产品-acc_concept 组合。这就是代码行“ df_2017 <-df_2017 [sample(1:195 * 65 * 39),450000),]”的原因,也是输出可能变为NA的原因(见下文)。
ratio_df中的列在哪里:
我想为每个公司内的每种产品计算acc_concept之间的2个比率(ratio_df)。
例如:
我从ratio_df中获取第一个比率“ acc_concepts”和“ name”:
num_acc_concept <- ratio_df[ratio_df$concept == "numerator", 2]
denom_acc_concept <- ratio_df[ratio_df$concept == "denom", 2]
ratio_name <- ratio_df[ratio_df$concept == "name", 2]
然后我计算一家公司的一种产品的比率,只是为了表明您想要我要做的事情:
ratio1_value <- sum(df_2017[df_2017$company == 1 & df_2017$product == 1 & df_2017$acc_concept %in% num_acc_concept, 4]) / sum(df_2017[df_2017$company == 1 & df_2017$product == 1 & df_2017$acc_concept %in% denom_acc_concept, 4])
输出:
output <- data.frame(Company="1", Product="1", desc_ratio=ratio_name, ratio_value = ratio1_value, stringsAsFactors = F)
就像我之前说的,我想对每个公司的每个产品执行此操作
输出data.frame可能是类似的东西(比率不是真正的比率,因为我还没有进行计算):
company product desc_ratio ratio_value
1 1 Sales over Assets 0.9303675
1 3 Sales over Assets 1.30
1 7 Sales over Assets Nan
1 1 Sales over Expenses A + B Inf
1 2 Sales over Expenses A + B 2.32
1 3 Sales over Expenses A + B NA
2
3
and so on...
我希望我已经清楚了...
有什么方法可以用dplyr解决此行问题吗?我应该投放df_2017吗?