当我使用 xts 包将数据帧转换为时间序列数据时,数字和整数变量在 R 中更改为字符变量

When I converted data frame into time series data by using xts package, numeric and interger variables was changed to character variables in R

我在 Rstudio 版本 4.0.2 上编写代码。我的数据包括股票的价格和数量。

当我 运行 我的代码时,数字和整数变量被更改为字符变量。

我不明白为什么会遇到这个问题以及如何修复此代码?如果有任何提示,我将不胜感激。

我的编码方式如下:

> original.HPG <- read.csv("excel_hpg.csv", header = TRUE)
> keep.variables.HPG <- original.HPG[,c(1,2,7:11)] 
> names(keep.variables.HPG) <- paste(c("HPG.Ticker", "HPG.Date", "HPG.Volume",
+                                "HPG.Open", "HPG.High", "HPG.Low", "HPG.Close"))
> library(lubridate)
> edit.date.HPG <- ymd(keep.variables.HPG[,2])
> class(edit.date.HPG)
[1] "Date"
> data.HPG <- cbind(edit.date.HPG, keep.variables.HPG[,-2])
> data.HPG <- data.HPG[order(data.HPG$edit.date.HPG),]
> data.HPG[c(1:3, nrow(data.HPG)), ]
     edit.date.HPG HPG.Ticker HPG.Volume HPG.Open HPG.High HPG.Low
3210    2007-11-15        HPG    1306330   130.00   130.00   109.0
3209    2007-11-16        HPG     248510   121.00   121.00   121.0
3208    2007-11-19        HPG     120480   115.00   115.00   115.0
1       2020-10-06        HPG   23609700    27.45    28.25    27.2
     HPG.Close
3210    127.00
3209    121.00
3208    115.00
1        28.25
> str(data.HPG)
'data.frame':   3210 obs. of  7 variables:
 $ edit.date.HPG: Date, format: "2007-11-15" "2007-11-16" ...
 $ HPG.Ticker   : chr  "HPG" "HPG" "HPG" "HPG" ...
 $ HPG.Volume   : int  1306330 248510 120480 58710 728080 266040 106370 135430 262120 131020 ...
 $ HPG.Open     : num  130 121 115 110 105 114 111 108 108 106 ...
 $ HPG.High     : num  130 121 115 110 114 114 114 110 108 107 ...
 $ HPG.Low      : num  109 121 115 110 105 110 110 107 105 106 ...
 $ HPG.Close    : num  127 121 115 110 114 114 110 109 105 107 ...
> library(xts)
> data.HPG <- xts(data.HPG[,2:6], order.by = data.HPG[,1])
> data.HPG[c(1:3, nrow(data.HPG)), ]
           HPG.Ticker HPG.Volume HPG.Open HPG.High HPG.Low 
2007-11-15 "HPG"      " 1306330" "130.00" "130.00" "109.00"
2007-11-16 "HPG"      "  248510" "121.00" "121.00" "121.00"
2007-11-19 "HPG"      "  120480" "115.00" "115.00" "115.00"
2020-10-06 "HPG"      "23609700" " 27.45" " 28.25" " 27.20"
> str(data.HPG)
An ‘xts’ object on 2007-11-15/2020-10-06 containing:
  Data: chr [1:3210, 1:5] "HPG" "HPG" "HPG" "HPG" "HPG" "HPG" "HPG" "HPG" ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:5] "HPG.Ticker" "HPG.Volume" "HPG.Open" "HPG.High" ...
  Indexed by objects of class: [Date] TZ: UTC
  xts Attributes:  
 NULL

从数据框中删除字符列。尝试:

library(xts)
data.HPG <- xts(data.HPG[,3:6], order.by = data.HPG[,1])