rr-googlesheets

How to write rownames into a spreadsheet with the googlesheets package in R?


I would like to write a data frame in a Google spreadsheet with the googlessheets package but the rownames isn't written in the first column.

My data frame looks like this :

> str(stats)
'data.frame':   4 obs. of  2 variables:
 $ Offensive: num  194.7 87 62.3 10.6
 $ Defensive: num  396.28 51.87 19.55 9.19

> stats
                                 Offensive   Defensive
Annualized Return               194.784261  396.278385
Annualized Standard Deviation     87.04125   51.872826
Worst Drawdown                    22.26618    9.546208
Annualized Sharpe Ratio (Rf=0%)   1.61126    0.9193734

I load the library as recommanded in the documentation, create spreadsheet & worksheet then write the data with the gs_edit_cells command :

> install.packages("googlesheets")
> library("googlesheets")
> suppressPackageStartupMessages(library("dplyr"))

> mySpreadsheet <- gs_new("mySpreadsheet")
> mySpreadsheet <- mySpreadsheet %>% gs_ws_new("Stats")
> mySpreadsheet <- mySpreadsheet %>% gs_edit_cells(ws = "Stats", input = stats, trim = TRUE)

Everything goes well but googlesheets doesn't create a column with the rownames. Only two columns are created with their data (Offensive and Defensive).

I have try to convert the data frame into a matrix but still the same.

Any idea how I could achieve this ?

Thank you


Solution

  • Doesn't look like there is a row names argument for gs_edit_cells(). If you just want the row names to show up in the first column of the sheet you could try:

    stats$Rnames = rownames(stats)                  ## add column equal to the row names
    stats[,c("Rnames","Offensive", "Defensive")]    ## re order so names are first
    # names(stats) = c("","Offensive", "Defensive") optional if you want the names col to not have a "name"
    

    From here just pass stats to the functions from the googlessheets package just like you did before