我有一个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
答案 0 :(得分:1)
您可以使用coredata
或storage.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
的警告。您应该检查源数据的完整性。