我有以下数据框:在数据帧创建百分比新列
dput(df1)
structure(list(month = c(1, 1, 2, 2, 3, 4), transaction_type = c("AAA",
"BBB", "BBB", "CCC",
"DDD", "AAA"), max_wt_per_month = c(54.9,
51.6833333333333, 52.3333333333333, 49.4666666666667, 49.85,
48.5833333333333), min_wt_per_month = c(0, 0, 0, 0, 0, 0), avg_wt_per_month = c(8.41701333107861,
7.65211141060198, 6.44184012508551, 7.74798927613941, 7.4360566888844,
7.50611319574734), prop = c(Inf, Inf, Inf, Inf, Inf, Inf)), .Names = c("month",
"transaction_type", "max_wt_per_month", "min_wt_per_month", "avg_wt_per_month",
"prop"), row.names = c(NA, -6L), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), vars = list(month), drop = TRUE, indices = list(
0:5), group_sizes = 6L, biggest_group_size = 6L, labels = structure(list(
month = 1), row.names = c(NA, -1L), class = "data.frame", vars = list(
month), drop = TRUE, .Names = "month"))
我想创建列prop
将包含的最长等待时间的百分比相对于每个月。如果我运行此代码,然后我得到Inf
值在大多数的行...(尤其是它在真实数据集是显而易见的):
my_fun=function(vec){
100*as.numeric(vec[3])/
sum(with(data_merged_transactions, ifelse(month == vec[1], max_wt_per_month, 0))) }
data_merged_transactions$prop=apply(data_merged_transactions , 1 , my_fun)
我后来终于需要创建填充区域图,使每个区域将是一个百分比超出了100%:
ggplot(data_merged_transactions, aes(x=month, y=prop, fill=transaction_type)) +
geom_area(alpha=0.6 , size=1, colour="black")
为什么我得到Inf
如果总和不等于0? 此外,是否可以创建以月份为因子(1月,2月等)的填充面积图,而不是数字?我试图用月份名称替换月份ID,但是后来我得到了很细的条而不是填充的区域。
你能给我们提供原始数据帧的输出吗?我正在努力导入你发布的那个?您还可以详细说明“每月最大等待时间的百分比”与数据集中其他变量的关系? – biomiha
@biomiha:真实的数据集很大。我刚刚发布了'dput(head(df))'。最大等待时间上的%意味着MAX_WT [AAA,1月]/SUM(MAX_WT [january])',其中max_wt是第3列,AAA是特定行的transaction_type。 – FiofanS