gpt4 book ai didi

r - 通过 rbind 向 data.frame 添加行会导致日期错误

转载 作者:行者123 更新时间:2023-12-04 10:15:44 27 4
gpt4 key购买 nike

我有这段代码每天向 R 中的冠状病毒数据框添加新行(来自 excel)。最奇怪的事情正在发生:即使我明确声明 Data="2020-04-05",添加到 rawData.Rda 的日期是“2020-04-04”,即该数据框的最新日期。此外,它突然开始显示此日期的时间:除新行之外的每一行都是 00:00:00,其中日期是 2020-04-04 23:00:00。这里发生了什么?解决这种情况或引入数据的新方法都是很好的解决方案。
PS:尝试添加 as.Date 但这并没有解决问题。

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

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"))

最佳答案

您没有将格式化的日期值分配给 rawData$DatanewData$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

关于r - 通过 rbind 向 data.frame 添加行会导致日期错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61067563/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com