Search code examples
rlistmatrixdatatable

Export table stored as list to Excel


I have balanced my population through WeightIt and I used bal.tab from cobalt package to create a table with the summary characteristics of my balanced population.

library(cobalt)
library(WeightIt)

data("lalonde", package = "cobalt")

W.out <- weightit(treat ~ age + educ + race + married + nodegree + re74 + re75,
                  data = lalonde, estimand = "ATT", method = "ps")

balanced_population <- bal.tab(W.out)
balanced_population

However, the results from bal.tab are stored as list, how can I save it as table or matrix and subsequently as an Excel file?

I found in another question this solution but I keep getting an error although I installed the package correctly - plus I don't know if it should work in this case:

expss::xl_write_file(table, filename="test.xlsx")
Error in loadNamespace(x) : there is no package called ‘openxlsx’

Can anyone please provide a solution? The simplest as possible. I just want to export the results so I don't have to copy all the numbers each time.


Solution

  • balanced.population is a named list:

    names(balanced_population)
    [1] "Balance"      "Observations" "call"
    

    So you can access each list element using e.g.

    balanced.population$Balance
    

    If you examine the structure of the list using

    str(balanced.population)
    

    you'll see that balanced.population$Balance is a data frame with 10 rows and 3 columns.

    There appears to be an issue with your installation of openxlsx. Personally I would not bother writing to an Excel file, when you can easily write to a CSV file which Excel can import.

    write.csv(balanced_population$Balance, "balance_data.csv")