r - 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
解决方案
您可以使用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
. 您应该检查源数据的完整性。
推荐阅读
- c# - 多个PDF MemoryStreams的iText7合并不起作用
- javascript - Javascript 复制数组。更改会影响两个数组
- mysql - 如何在 Windows 10 机器上禁用 MySQL 8.0 中的 secure_file_priv?
- html - 其他文本框返回旧值,如何使我的文本框为空白?
- rust - 如何降级 Rc
> 进入弱 ? - html - Bootstrap Sticky-top 类在 main-content 类中不起作用
- python - pyinstaller 和 sklearn 不兼容
- python-3.x - 为什么我的 Crontab 没有在特定时间运行?
- go - Logger.Writer.(*os.File) (左侧的非接口类型 func() io.Writer)
- java - 无法选择麦克风 TargetDataLine。似乎,我只能使用我的操作系统系统默认的输入