3

I want to add a total row (as in the Excel tables) while writing my data.frame in a worksheet. Here is my present code (using openxlsx):

writeDataTable(wb=WB, sheet="Data", x=X, withFilter=F, bandedRows=F, firstColumn=T)

X contains a data.frame with 8 character variables and 1 numeric variable. Therefore the total row should only contain total for the numeric row (it will be best if somehow I could add the Excel total row feature, like I did with firstColumn while writing the table to the workbook object rather than to manually add a total row).

I searched for a solution both in StackOverflow and the official openxslx documentation but to no avail. Please suggest solutions using openxlsx.

EDIT:

Adding data sample:

A  B  C  D  E  F  G  H  I
a  b  s  r  t  i  s  5  j
f  d  t  y  d  r  s  9  s
w  s  y  s  u  c  k  8  f

After Total row:

    A  B  C  D  E  F  G  H  I
    a  b  s  r  t  i  s  5  j
    f  d  t  y  d  r  s  9  s
    w  s  y  s  u  c  k  8  f
    na na na na na na na 22 na
Arani
  • 753
  • 1
  • 9
  • 23

2 Answers2

1

Assuming your data is stored in a data.frame called df:

df <- read.table(text = 
    "A  B  C  D  E  F  G  H  I
    a  b  s  r  t  i  s  5  j
    f  d  t  y  d  r  s  9  s
    w  s  y  s  u  c  k  8  f", 
                 header = TRUE,
                 stringsAsFactors = FALSE)

You can create a row using lapply

totals <- lapply(df, function(col) {
  ifelse(!any(!is.numeric(col)), sum(col), NA)
})

and add it to df using rbind()

df <- rbind(df, totals)

head(df)
     A    B    C    D    E    F    G  H    I
1    a    b    s    r    t    i    s  5    j
2    f    d    t    y    d    r    s  9    s
3    w    s    y    s    u    c    k  8    f
4 <NA> <NA> <NA> <NA> <NA> <NA> <NA> 22 <NA>
clemens
  • 6,653
  • 2
  • 19
  • 31
1
library(janitor)
adorn_totals(df, "row")

#>      A B C D E F G  H I
#>      a b s r t i s  5 j
#>      f d t y d r s  9 s
#>      w s y s u c k  8 f
#>  Total - - - - - - 22 -

If you prefer empty space instead of - in the character columns you can specify fill = "" or fill = NA.

Sam Firke
  • 21,571
  • 9
  • 87
  • 105