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
4

2 回答 2

1

假设您的数据存储在名为 df 的 data.frame 中:

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)

您可以使用创建一行lapply

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

并将其添加到df使用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>
于 2017-10-11T07:06:29.373 回答
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 -

如果您更喜欢空格而不是-字符列,您可以指定fill = ""fill = NA

于 2019-08-03T02:29:24.283 回答