-2

Hi I have a sample dataset like this. What I would like to do is to calculate the sum of column "Number" and append it to the last row. I understand that I can use the package "Janitor" to provide the ideal result but my work device does not have the updated version of R. So I am trying to figure a way to do the same thing.

Sample Dataset

#using janitor library
df = df%>%
 adorn_totals("row")

Ideal Result

Another way of solving it would be to calculate the sum of column using

x = sum(df$Number)

but I have no idea how to append x into df

dummy123
  • 31
  • 6

2 Answers2

1

You can also use dplyr with bind_rows() function. Here an example using dummy data. Inside bind_rows() you have to compute the total value:

library(dplyr)
set.seed(123)
#Data
df <- data.frame(Code=sample(c('YE','RE','PU','WH'),20,replace = T),
                 Color=sample(c('yellow','red','green'),20,replace = T),
                 Number=round(runif(20,1,15),0),stringsAsFactors = F)
#Create total
df %>%
  bind_rows(df %>% summarise(Number=sum(Number,na.rm=T)) %>% mutate(Code='Total'))

Output:

    Code  Color Number
1     PU yellow      3
2     PU yellow      4
3     PU yellow      8
4     RE yellow      5
5     PU  green     13
6     RE    red      2
7     RE  green      7
8     RE    red     12
9     PU yellow      3
10    YE    red      9
11    WH  green      4
12    RE    red      3
13    RE yellow     12
14    YE  green     14
15    RE  green      6
16    PU yellow     10
17    WH  green      2
18    YE    red      6
19    PU yellow      5
20    PU  green     12
21 Total   <NA>    140
Duck
  • 39,058
  • 13
  • 42
  • 84
0

Assuming your dataset is called df, you can use rbind and sum:

rbind(df, sum(df$Number))
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34