首页 > 解决方案 > xts 将数据从 chr 转换为 numeric

问题描述

我有一个 xts 对象table2,但存储在其中的数据在 chr 中,如何将其更改为数字?我尝试使用 as.numeric 但它放弃了我的 xts 格式。

An ‘xts’ object on 2010-11-15/2018-06-01 containing:
Data: chr [1:2052, 1:6] "1.3705" "1.3586" "1.3486" "1.3526" "1.3641" 
"1.37176" "1.3718" ...
 - attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:6] "Open" "High" "Low" "Close" ...
Indexed by objects of class: [POSIXct,POSIXt] TZ: 
xts Attributes:  
NULL

标签: rxtsnumericchr

解决方案


您可以使用coredatastorage.mode更改数据的基础类型。

library(xts)
x <- xts(1:5, Sys.Date()-4:0)
str(x)
# An 'xts' object on 2018-06-11/2018-06-15 containing:
#   Data: int [1:5, 1] 1 2 3 4 5
#   Indexed by objects of class: [Date] TZ: UTC
#   xts Attributes:  
#  NULL
coredata(x) <- as.character(coredata(x))
str(x)
# An 'xts' object on 2018-06-11/2018-06-15 containing:
#   Data: chr [1:5, 1] "1" "2" "3" "4" "5"
#   Indexed by objects of class: [Date] TZ: UTC
#   xts Attributes:  
#  NULL
storage.mode(x) <- "integer"
str(x)
# An 'xts' object on 2018-06-11/2018-06-15 containing:
#   Data: int [1:5, 1] 1 2 3 4 5
#   Indexed by objects of class: [Date] TZ: UTC
#   xts Attributes:  
#  NULL

请注意,您的 xts 对象可能是字符,因为您导入的文件中有非数字值。因此,您应该会收到有关某些值被转换为NA. 您应该检查源数据的完整性。


推荐阅读