0

I currently have a dataframe in R named as df. The df looks something like this:

con A B C D

ab 24 34 2 16

ba 47 12 23 21

cd 23 1 2 32

Now, i want the sum of all the rows(ab,ba,cd...n) in each column (A,B,C,D....n) and add or append one row at the bottom with all total values. After the sum, the data should look something like this:

con A B C D

ab 24 34 2 16

ba 47 12 23 21

cd 23 1 2 32

sum 94 47 27 69

Ric S
  • 9,073
  • 3
  • 25
  • 51

1 Answers1

1

We can use add_margins from base R after converting the numeric columns to a matrix and changing the row names as 'con' column

addmargins(`row.names<-`(as.matrix(df1[-1]), df1$con), 1)
#     A  B  C  D
#ab  24 34  2 16
#ba  47 12 23 21
#cd  23  1  2 32
#Sum 94 47 27 69

or with adorn_totals from janitor

library(janitor)
df1 %>% 
    adorn_totals(name = 'Sum')
#  con  A  B  C  D
#  ab 24 34  2 16
#  ba 47 12 23 21
#  cd 23  1  2 32
# Sum 94 47 27 69

data

df1 <- structure(list(con = c("ab", "ba", "cd"), A = c(24L, 47L, 23L
), B = c(34L, 12L, 1L), C = c(2L, 23L, 2L), D = c(16L, 21L, 32L
)), class = "data.frame", row.names = c(NA, -3L))
akrun
  • 874,273
  • 37
  • 540
  • 662