rgoogle-sheets-apir-googlesheets

Integer interpreted as date when added to Google Sheets by R + googlesheets


I am trying to add pairs of values (date, value) to Google Sheets via gs_add_row from googlesheets. This succeeds, except that both values show up as dates on Google Sheets.

I checked the "value" beforehand to make sure it is as expected (eg. 50), but Sheets displays a date (1970-02-20).

I even tried setting the cell formatting in Sheets to "Numbers" instead of "Automatic" but it made no difference.

Is there a way to specify variable types?

EDIT Example code:

library(lubridate)
library(googlesheets)
library(dplyr)

#URL <- "[some 'published to the web' Google Sheet URL]"
dt <- ymd(today())
val <- 50

URL %>% 
    gs_url() %>% 
    gs_add_row(ws=3, input = c(dt, val))

Solution

  • The issue arises from the usage of c to concatenate dt and val into a vector. when you use c, the output type is determined from the highest type of the components in the hierarchy NULL < raw < logical < integer < double < complex < character < list < expression. Therefore, the output of the concatenation (using c) is of Date class in this case. If you had done c(val, dt), the output type would be numeric.

    Your best bet is to do:

    URL %>%
        gs_url() %>% 
        gs_add_row(ws=3, input = c(as.character(dt), val))
    

    If this does not work the first time around, you may have to delete the old Sheet, make a new Sheet with the same data, and run the code on the new sheet.

    Thanks!