2

I am trying to add the sum (of all the counts in a specific vector) in my data frame in R. Specifically, I want to keep all the counts and then add a sum at the end. In excel, you would do =sum(A1:A5232). Additionally, I don't know the length of the specific vector. See below:

#sumarize by colname
  NewDepartment <- List %>%
  group_by(NewDepartment) %>%
  tally(sort=TRUE)

The above code will give me the following:

                   NewDepartment     n
                       <chr> <int>
1                           <NA>   709
2                    Collections   454
3                      Telesales   281
4  Operations Control Management    93
5                   Underwriting    92

I want a total count at the end like this:

                   NewDepartment     n
                       <chr> <int>
1                           <NA>   709
2                    Collections   454
3                      Telesales   281
4  Operations Control Management    93
5                   Underwriting    92
6                   Total Sum       1721

How do I get the row # 6 above??

  • @MikeH. It looks like `NewDepartment` is a column (as well as a data.frame), and the row names are integers, so I don't think your syntax will work. – Gregor Thomas May 02 '17 at 22:01

1 Answers1

3

Try this:

NewDepartment = rbind(NewDepartment, 
    data.frame(NewDepartment = "Total Sum", n = sum(NewDepartment$n)))
lebelinoz
  • 4,890
  • 10
  • 33
  • 56
  • Thank you! Worked. Is it possible to write that in one piece though? Meaning, if I changed the data.frame name to say "Final Department"? ##sumarize by colname FinalDepartment <- List %>% group_by(NewDepartment) %>% tally(sort=TRUE) %>% FinalDepartment = rbind(FinalDepartment , data.frame(NewDepartment = "Total Sum", n = sum(FinalDepartment $n))) – LeoTheLioin6789 May 03 '17 at 13:59