Reputation: 1393
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)
)
Upvotes: 0
Views: 74
Reputation: 11255
Here's a base way. It's ok.
DF_summary <- colSums(DF[, -1])
DF_summary[4] <- mean(DF[, 5])
rbind(DF, c('Total',DF_summary))
Site Counts Cost Views Average avg_views
1 Channel1 7637587 199999.993061 3007915 2.54 7.5197875
2 Channel2 19042385 102196.9726 5897235 3.23 14.7430875
3 Channel3 72019057 102574.79 14245859 5.05543800482653 35.6146475
4 Channel4 45742745 196174.712132 24727451 2.21111111111111 48.24
5 Total 144441774 600946.467793 47878460 3.25913727898441 106.1175225
Upvotes: 0
Reputation: 1771
I'm not sure if this can help you but that's what I'm using when I want to add a Total row at the end. I also use this with the data.table
package.
Code example:
dt <- rbind(dt, data.table(Site = "Total",
Counts = sum(dt[, Counts]),
Cost = sum(dt[, Cost]),
Views = mean(dt[, Views]),
Average = sum(dt[, Average]),
avg_views = paste("Hi OP")))
Output :
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 11969615 13.036549 Hi OP
You can apply whatever functions you want. In my code example you have sum()
and also mean()
but you could use anything.
Upvotes: 2