Search code examples
rexport-to-csv

How to NOT write_csv if data frame is empty


I have a dataframe that is gathered everyday via a sql query. Sometimes it'll have rows in it, sometimes it wont. I then write_csv it into a onedrive location which triggers an automated email.

df and code like this if relevant:

df<-structure(list(PROTOCOL_ID = numeric(0), PROTOCOL_NO = character(0), 
    STATUS = character(0), STATUS_DATE = structure(numeric(0), tzone = "", class = c("POSIXct", 
    "POSIXt")), PROCESSED_FLAG = character(0), INITIATOR_CODE = numeric(0), 
    CHANGE_REASON_CODE = numeric(0), PR_STATUS_ID = numeric(0), 
    COMMENTS = character(0), CREATED_DATE = structure(numeric(0), tzone = "", class = c("POSIXct", 
    "POSIXt")), CREATED_USER = character(0), MODIFIED_DATE = structure(numeric(0), tzone = "", class = c("POSIXct", 
    "POSIXt")), MODIFIED_USER = character(0), OUTCOME_ID = numeric(0), 
    IRB_NO = character(0), NCT_NUMBER = character(0), PI_NAMES = character(0)), row.names = integer(0), class = "data.frame")
write_csv(df, "df.csv")

If the dataframe has zero rows that day, I'd rather it DIDN'T write the csv. I'm sure I could figure out a step that deletes the data frame if empty and then the write_csv line would error, but I'd rather not do that. Is there an easy way to 'turn off' the write?


Solution

  • We could have a condition to only write to csv when the number of rows is greater than 0

    if(nrow(df) > 0) readr::write_csv(df, "df.csv")