Home > database >  How to find the sum total of a column?
How to find the sum total of a column?

Time:10-30

I'm trying to get the sum of n from a count table. I'm able to do this with this:

mtcars %>% 
  count(cyl) %>% 
  pull(n) %>% 
  sum()

Is there a one-line way to do this in base R. The purpose of the value is to add this as a caption on a table like this:

mtcars %>% 
  count(cyl) %>% 
  kable(caption = "n =  (insert value here")

I actually want to count the total of the n because in my real pipe workflow I filter the data frame.

mtcars %>% 
  filter(vs == 1) %>% 
  count(cyl)

#   cyl  n
# 1   4 10
# 2   6  4

In this case, I would like it to be 14 (10 4) which is the sum of n and not 32.

Something like this solution: Temporarily store variable in series of pipes dplyr

CodePudding user response:

You may use nrow to count the number of rows in data -

library(dplyr)
library(knitr)

mtcars %>% 
  count(cyl) %>% 
  kable(caption = paste0("n = ", nrow(mtcars)))

#Table: n = 32

#| cyl|  n|
#|---:|--:|
#|   4| 11|
#|   6|  7|
#|   8| 14|

CodePudding user response:

We can do this by a simple sum and referring to the n column within the pipe;

library(dplyr)
library(knitr)

mtcars %>% 
  filter(vs == 1) %>% 
  count(cyl) %>% 
  kable(caption = paste0("n = ", sum(.$n)))

n = 14

cyl n
4 10
6 4

If you're counting all the rows, this can be done using dplyr::tally as well;

library(dplyr)
library(knitr)

mtcars %>% 
  count(cyl) %>% 
  kable(caption = paste0("n = ", tally(mtcars)))

CodePudding user response:

We may also use with

library(dplyr)
library(knitr)
mtcars %>% 
  count(cyl) %>% 
  kable(format = "pipe", caption = glue::glue("n = {with(., sum(n))}"))

-output

Table: n = 32

| cyl|  n|
|---:|--:|
|   4| 11|
|   6|  7|
|   8| 14|
  • Related