0

I am exploring some data with R, and looking for smart method for computing a new row with the total of the numeric columns. I give below a dummy example :

tibble(
  Group = c("Crew", "1st class", "2nd class", "3rd class"),
  Deaths = c(673, 122, 167, 528),
  Survivors = c(212, 203, 118, 178)
) %>%
  add_row(Group = "Total", Deaths = sum(.$Deaths), 
          Survivors = sum(.$Survivors)) 

I am not really satisfied of this code, and wonder wether it exists a more elegant method using dplyr. But it leads me to a simple question : why can't I replace .$Deaths by .data$Deaths ? I often develop package and I am always struggle for removing the checking notes. In that case, I would not be able to remove the dot expression... Can anyone provide an alternative solution or at least an explanation ?

Thanks in advance ;-)

2 Answers2

2

You could try janitor::adorn_totals which is at least cleaner.

tibble(
  Group = c("Crew", "1st class", "2nd class", "3rd class"),
  Deaths = c(673, 122, 167, 528),
  Survivors = c(212, 203, 118, 178)
) %>% janitor::adorn_totals()

#     Group Deaths Survivors
#      Crew    673       212
# 1st class    122       203
# 2nd class    167       118
# 3rd class    528       178
#     Total   1490       711
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • I agree it is a cleaner way, but it requires a new package... I've already consider this usage but I prefer not to. Anyway, thanks for the answer ! – Jeffery Petit Oct 27 '20 at 12:26
0

If you want to do it step-by-step:
(that's longer code, but maybe better in some cases?)

# define tibble
df <- tibble(
  Group = c("Crew", "1st class", "2nd class", "3rd class"),
  Deaths = c(673, 122, 167, 528),
  Survivors = c(212, 203, 118, 178)
  )
  
# summarize the two columns
df_add <- df %>%
  summarize(Group = "Total",
            Deaths = sum(Deaths),
            Survivors = sum(Survivors))

# add to tibble
df <- df %>%
  add_row(df_add)
j_5chneider
  • 390
  • 5
  • 15