无法从含正确格式日期索引的Data.Frame创建xts对象
问题:data.frame转xts对象失败,提示order.by需要时间类型对象
转换带有日期索引的data.frame为xts对象时,出现如下错误:
Error in xts(master_zillow5) : order.by requires an appropriate time-based object
用户使用的脚本:
master_zillow4[,1] <- as.Date(master_zillow4[,1]) master_zillow5 <- master_zillow4 %>% column_to_rownames(., var = 'Date') test <- xts(master_zillow5,order.by = index(master_zillow5)) index(test) <- mdy(index(test))
master_zillow5的样本数据:
structure(list(`77449` = c(112055.39, 112074.39), `77494` = c(221254.91, 221443.2), `79936` = c(92921.09, 92903.53), `11368` = c(272971.91, 275503.86), `11385` = c(247208.49, 248297.55), `90011` = c(119682.49, 120141.32), `60629` = c(85923.22, 85887.92), `77084` = c(111978.96, 111930.09), `91331` = c(141705.13, 141906.18), `90650` = c(175432.71, 175560.59), ` 8701` = c(154371.71, 155046.85), `11236` = c(202347.35, 203171.26), `90201` = c(151762.67, 151854.87), `92335` = c(109520.6, 110306.38), `11208` = c(169135.26, 169468.6), `10467` = c(151250.38, 152186.03), `11226` = c(227102.62, 228847.7), `78660` = c(181774.38, 182131.03), `92503` = c(158099.49, 158438.13), `90250` = c(193337.36, 193665.76)), row.names = c("2000-01-31", "2000-02-29"), class = "data.frame")
问题原因与解决方法
核心问题
index(master_zillow5) 提取的是data.frame的字符型行名,并非xts要求的时间类对象(如Date、POSIXct);且后续用mdy()转换格式错误,因为行名是YYYY-MM-DD格式,mdy()适用于月-日-年结构的字符串。
修正方案1:直接用原始Date列构建xts
无需将Date转为行名,直接用原始Date列作为时间索引:
# 确保Date列是Date类型 master_zillow4$Date <- as.Date(master_zillow4$Date) # 构建xts:数据部分排除Date列,order.by指定为Date列 test <- xts(master_zillow4[, -which(names(master_zillow4) == "Date")], order.by = master_zillow4$Date)
修正方案2:从行名转换为Date后构建xts
若已将Date转为行名,需先把行名转成Date类型再传入:
# 把字符型行名转换为Date对象 date_index <- as.Date(rownames(master_zillow5)) # 构建xts对象 test <- xts(master_zillow5, order.by = date_index)
原代码的错误点
index(master_zillow5)对data.frame无效:xts的index()函数仅适用于xts对象,对data.frame调用会返回字符型行名,无法被xts识别为时间索引。mdy(index(test))格式不匹配:行名是YYYY-MM-DD,应使用ymd()或as.Date()转换,而非mdy()。
内容的提问来源于stack exchange,提问作者js80
相关产品推荐
相关产品推荐

