user3206440
user3206440

Reputation: 5059

change columns names of aggregation output

I use the below function to perform an aggregation operation which computes share by certain labels.

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")

This gives output df_out like below with

          colx          coly
1         name1 1.897315e-02
2         name2 2.988709e-04
3         name3 7.081621e-04

Instead of column name coly in df_out above, I want the name Share. I can do it via colnames(df_out)[2] <- "Share" inside the function like below.

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

    }

Is this the right way to do this ?

Upvotes: 0

Views: 1684

Answers (1)

enroute
enroute

Reputation: 183

have you tried setNames(aggregate(...), c("group","Share")) ?

Upvotes: 1

Related Questions