DaltonicD
DaltonicD

Reputation: 75

Adding rows to data.frame through rbind causes error with dates

I have this code to add a new row each day to my coronavirus dataframe in R (came from excel). The weirdest thing is happening: even though I clearly state Data="2020-04-05", the date added to rawData.Rda is "2020-04-04", the latest date of that dataframe. Furthermore, it suddenly starts showing a time for this date: 00:00:00 for every row except the new one, where date is 2020-04-04 23:00:00. What is going on here? Both a fix to the situation or a new way to introduce data would be good solutions. PS: tried to add as.Date but this did not solve the problem.

load("rawdata.Rda")
as.Date(rawData$Data, format="%Y-%m-%d")
newData <- data.frame(Data = "2020-04-05", Casos=11278, Óbitos = 295, Recuperados = 75)
as.Date(newData$Data, format="%Y-%m-%d")
rawData <- rbind(rawData, newData)

rawData initially

rawData initially

rawData after running the aforementioned code

rawData after running the aforementioned code

rawData <- structure(list(Data = structure(c(1583107200, 1583193600, 1583280000, 
1583366400, 1583452800, 1583539200, 1583625600, 1583712000, 1583798400, 
1583884800, 1583971200, 1584057600, 1584144000, 1584230400, 1584316800, 
1584403200, 1584489600, 1584576000, 1584662400, 1584748800, 1584835200, 
1584921600, 1585008000, 1585094400, 1585180800, 1585267200, 1585353600, 
1585440000, 1585526400, 1585612800, 1585699200, 1585785600, 1585872000, 
1585958400), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
    Casos = c(2, 4, 6, 9, 13, 21, 30, 39, 41, 59, 78, 112, 169, 
    245, 331, 448, 642, 785, 1020, 1280, 1600, 2060, 2362, 2995, 
    3544, 4268, 5170, 5962, 6408, 7443, 8251, 9034, 9886, 10524
    ), Óbitos = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
    1, 2, 3, 6, 12, 14, 23, 24, 43, 60, 76, 100, 119, 140, 160, 
    187, 209, 246, 267), Recuperados = c(0, 0, 0, 0, 0, 0, 0, 
    0, 0, 0, 0, 0, 1, 2, 3, 3, 3, 3, 5, 5, 5, 14, 22, 22, 43, 
    43, 43, 43, 43, 43, 43, 68, 68, 75)), row.names = c(NA, -34L
), class = c("tbl_df", "tbl", "data.frame"))

Upvotes: 2

Views: 642

Answers (1)

Sathish
Sathish

Reputation: 12713

You are not assigning formatted date values to rawData$Data and newData$Data.

rawData$Data <- as.Date(rawData$Data, format="%Y-%m-%d")
newData <- data.frame(Data = "2020-04-05", Casos=11278, Óbitos = 295, Recuperados = 75)
newData$Data <- as.Date(newData$Data, format="%Y-%m-%d")
rawData <- do.call('rbind', list(rawData, newData))
head(rawData)
#         Data Casos Óbitos Recuperados
# 1 2020-03-02     2      0           0
# 2 2020-03-03     4      0           0
# 3 2020-03-04     6      0           0
# 4 2020-03-05     9      0           0
# 5 2020-03-06    13      0           0
# 6 2020-03-07    21      0           0

Upvotes: 3

Related Questions