How to do colsum and average on the same dataframe

I am trying to add a new row to this dataframe below name total. Now for the columns counts,cost,views are colsums or totals but for average I want to do average and for average I want to do a custom formula .So how can I do that. I did use the janitor library (adorn_totals("row"))but it just does the sum . Below is the sample dataframe:

data.frame(stringsAsFactors=FALSE,
                Site = c("Channel1", "Channel2", "Channel3", "Channel4"),
         Counts = c(7637587, 19042385, 72019057, 45742745),
                Cost = c(199999.993061, 102196.9726, 102574.79, 196174.712132),
    Views = c(3007915, 5897235, 14245859, 24727451),
   Average = c(2.54, 3.23, 5.05543800482653, 2.21111111111111),
               avg_views = c(7.5197875, 14.7430875, 35.6146475, 48.24)
)

I am not sure I understand what you are after. Is it something like this?

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
df <- data.frame(stringsAsFactors=FALSE,
           Site = c("Channel1", "Channel2", "Channel3", "Channel4"),
           Counts = c(7637587, 19042385, 72019057, 45742745),
           Cost = c(199999.993061, 102196.9726, 102574.79, 196174.712132),
           Views = c(3007915, 5897235, 14245859, 24727451),
           Average = c(2.54, 3.23, 5.05543800482653, 2.21111111111111),
           avg_views = c(7.5197875, 14.7430875, 35.6146475, 48.24)
)
NewRow <- df %>% summarize(Site = "Total",
  Counts = sum(Counts), Cost = sum(Cost), Views = sum(Views),
                           Average = mean(Average), avg_views = mean(avg_views))
dfNew <- rbind(df, NewRow)
dfNew
#>       Site    Counts     Cost    Views  Average avg_views
#> 1 Channel1   7637587 200000.0  3007915 2.540000  7.519787
#> 2 Channel2  19042385 102197.0  5897235 3.230000 14.743087
#> 3 Channel3  72019057 102574.8 14245859 5.055438 35.614647
#> 4 Channel4  45742745 196174.7 24727451 2.211111 48.240000
#> 5    Total 144441774 600946.5 47878460 3.259137 26.529381

Created on 2019-07-30 by the reprex package (v0.2.1)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.