我使用以下函数执行聚合操作,该操作通过某些标签计算份额。
computeShare <- function(df, colX, colY) {
aggregate(as.formula(paste0(colY, '~', colX)),
df, function(x){length(x)/nrow(df)})
}
df_out <- computeShare(some_df, "colx", "coly")
这会使输出df_out
如下所示
colx coly
1 name1 1.897315e-02
2 name2 2.988709e-04
3 name3 7.081621e-04
而不是上面coly
中的列名df_out
,我想要名称Share
。我可以通过以下函数中的colnames(df_out)[2] <- "Share"
来完成。
computeShare <- function(df, colX, colY) {
df_out <- aggregate(as.formula(paste0(colY, '~', colX)),
df, function(x){length(x)/nrow(df)})
colnames(df_out)[2] <- "Share"
df_out
}
这是正确的方法吗?
答案 0 :(得分:0)
你试过setNames(aggregate(...), c("group","Share"))
吗?