I create a two way table in R using the following code
t <- table(df[["Sex"]], df[["C or Better"]], useNA = "ifany")
colnames(t)[is.na(colnames(t))] <- "Blank"
CountsBySex <- addmargins(t, c(1,2))
This works just fine, and I can print the table without a problem
> t
C-, D or F Other Pass Blank
F 1967 737 3169 106
M 1555 480 2452 71
But when I write the table to Excel as follows, the contents of the Excel file look weird:
wb <- openxlsx2::wb_add_data(wb, sheet = cs, CountsBySex,
start_col = 1, start_row = writeRow)
Var1 Var2 Freq
1 F C-, D or F 1967
2 M C-, D or F 1555
3 Sum C-, D or F 3522
4 F Other 737
5 M Other 480
6 Sum Other 1217
7 F Pass 3169
8 M Pass 2452
9 Sum Pass 5621
10 F Blank 106
11 M Blank 71
12 Sum Blank 177
13 F Sum 5979
14 M Sum 4558
15 Sum Sum 10537
It appears that openxlsx2 first converts my table to a data frame using as.data.frame(CountsBySex) and then writes it to Excel. What change do I need to make to my syntax to write my table to Excel as a table, and not as a data.frame? Interestingly, this problem does not arise when I use openxlsx - it writes the table to Excel correctly.
Many thanks in advance
Thomas Philips
Figured it out: I needed
as.data.matrix: