虚拟数据:
d <- data.frame(company=letters[1:26],
department=sample(letters[1:10],26,replace=TRUE),
region=sample(letters[1:3],26,replace=TRUE),
revenue=round(runif(26)*10000))
更新
我认为有必要对您的代码进行解释:
d_ply(dataframe, .(company), function(df) { # by company
d_ply(df, .(department), function(df) { # by department
d_ply(df, .(region), function(df) { # by region
bar_chart(df$region, df$revenue)
# this part is essentially equal to
# d_ply(df, .(company,department,region), function(df), plot(df))
})
bar_chart(df$department, df$revenue)
# this part is essentially equal
# d_ply(df,.(company,department), function(df), fun(df))
})
bar_chart(df$company, df$revenue)
# this part is essentially equal to
# d_ply(df,.(company), function(df), fun(df))
})
我发现您的代码非常难以阅读。它可以替换为:
some.fun <- function(df, ...) {
# ...
}
d_ply(d, .(company), function(df) some.fun(df, ...))
d_ply(d, .(company,department), function(df) some.fun(df, ...))
d_ply(d, .(company,department,region), function(df) some.fun(df, ...))