R - 在 Excel 输出中添加总计行
R - Adding a total row in Excel output
我想在工作表中写入 data.frame 时添加总行(如 Excel table 中的行)。
这是我现在的代码(使用 openxlsx
):
writeDataTable(wb=WB, sheet="Data", x=X, withFilter=F, bandedRows=F, firstColumn=T)
X 包含一个带有 8 个字符变量和 1 个数字变量的 data.frame。因此,总计行应该只包含数字行的总计(如果我能以某种方式添加 Excel 总计行功能,就像我在将 table 写入工作簿对象时对 firstColumn 所做的那样,那将是最好的而不是手动添加总行)。
我在 Whosebug 和官方 openxslx 文档中搜索了解决方案,但无济于事。请使用 openxlsx
.
建议解决方案
编辑:
添加数据示例:
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
在总行之后:
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
假设您的数据存储在一个名为 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)
})
并使用 rbind()
将其添加到 df
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>
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 -
如果您更喜欢在字符列中留空 space 而不是 -
,您可以指定 fill = ""
或 fill = NA
.
我想在工作表中写入 data.frame 时添加总行(如 Excel table 中的行)。
这是我现在的代码(使用 openxlsx
):
writeDataTable(wb=WB, sheet="Data", x=X, withFilter=F, bandedRows=F, firstColumn=T)
X 包含一个带有 8 个字符变量和 1 个数字变量的 data.frame。因此,总计行应该只包含数字行的总计(如果我能以某种方式添加 Excel 总计行功能,就像我在将 table 写入工作簿对象时对 firstColumn 所做的那样,那将是最好的而不是手动添加总行)。
我在 Whosebug 和官方 openxslx 文档中搜索了解决方案,但无济于事。请使用 openxlsx
.
编辑:
添加数据示例:
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
在总行之后:
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
假设您的数据存储在一个名为 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)
})
并使用 rbind()
df
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>
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 -
如果您更喜欢在字符列中留空 space 而不是 -
,您可以指定 fill = ""
或 fill = NA
.