R 创建具有不同行数的日期的XT

R 创建具有不同行数的日期的XT,r,xts,R,Xts,尝试创建一个xts文件,但在加载时格式化后,日期的行数与数据的行数不同。我的数据有许多列,行数不同,从20到200不等。我想在加载后创建一个单独的变量,带的变量取决于我想查看的组合,因此我想在创建变量之前使用NAs创建一个完整的data.frame,其中我将忽略并减少维度 代码如下: #load file with desired composite allcomposites <- read.csv("Composites 2014.08.31.csv", header = T) com

尝试创建一个xts文件,但在加载时格式化后,日期的行数与数据的行数不同。我的数据有许多列,行数不同,从20到200不等。我想在加载后创建一个单独的变量,带的变量取决于我想查看的组合,因此我想在创建变量之前使用NAs创建一个完整的data.frame,其中我将忽略并减少维度

代码如下:

#load file with desired composite
allcomposites <- read.csv("Composites 2014.08.31.csv", header = T)
compositebench <- allcomposites[1, 2:ncol(allcomposites)]
dates1 <- as.Date(allcomposites$Name, format = "%m/%d/%Y")
allcomposites <- as.data.frame(lapply(allcomposites[2:nrow(allcomposites),2:ncol(allcomposites)],    as.numeric))
allcomposites <- as.xts(allcomposites, order.by = dates1)
## Error in xts(x, order.by = order.by, frequency = frequency, ...) :
##     NROW(x) must match length(order.by)

dates1
以及
allcomposites
中删除第一行时需要更加小心

以下是实现目标的另一种方法:

Lines <- "Name    Composite1  Composite2  Composite3  Composite4 Composite5
Bmark   229 229 982 612 995
8/31/2014   0.9979  0.9404  4.3808      3.9296
7/31/2014   -0.4563 -0.3038 -1.7817     -1.7248
6/30/2014   0.205   0.2234  2.2184      2.7304
5/31/2014   1.311   1.5771  3.4824      1.7601
4/30/2014   0.9096  1.0187  -1.9195     1.2964"

library(xts)
# use fill=TRUE because you only provided data for 4 composites
allcomp <- read.table(text=Lines, header=TRUE, fill=TRUE)
# remove the first row that contains "Bmark"
allcomp <- allcomp[-1,]
# create an xts object from the remaining data
allcomp_xts <- xts(allcomp[,-1], as.Date(allcomp[,1], "%m/%d/%Y"))
行
我浪费了好几个小时才遇到这个错误。无论我是否遇到了完全相同的问题,我都将展示如何解决此错误消息,以防它为您省去了我的痛苦

我通过几个导入函数导入了一个Excel或CSV文件(尝试了两者),然后尝试将我的数据(作为data.frame或.zoo对象)转换为一个xts对象,并不断出现错误,包括这一个

我尝试分别创建一个日期向量,作为order.by参数传入。我尝试确保data.frame的行的日期向量是相同的。有时有效,有时无效,原因我无法解释。即使它真的起作用了,R也将我所有的数字数据“强制”为字符数据。(后来给我带来了无尽的麻烦。我明白了,要注意强迫。)

这些错误一直发生,直到:

对于xts转换,我使用导入的Excel工作表中的日期列作为带有as.date()修饰符的order.by参数,并*在转换为xts时删除了日期列。*

以下是工作代码:

xl_sheet <- read_excel("../path/to/my_excel_file.xlsx")
sheet_xts <- xts(xl_sheet[-1], order.by = as.Date(xl_sheet$date))

xl\u sheet您能举一个allcomposites看起来像什么的小例子吗?一个问题是,allcomposites$Name中包含了Bmark,您试图将Bmark转换为日期。正如@DMT所说:您需要忽略
dates1
dates1中的第一个观察值
## Error in xts(x, order.by = order.by, frequency = frequency, ...
##     NROW(x) must match length(order.by)
xl_sheet <- read_excel("../path/to/my_excel_file.xlsx")
sheet_xts <- xts(xl_sheet[-1], order.by = as.Date(xl_sheet$date))