【问题标题】:xts convert data from chr to numericxts 将数据从 chr 转换为 numeric
【发布时间】:2018-06-15 23:23:34
【问题描述】:

我有一个 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

【问题讨论】:

  • 您可以发布示例数据吗?请使用dput(head(table2, 10)) 的输出编辑问题。

标签: r xts numeric chr


【解决方案1】:

您可以使用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 的警告。您应该检查源数据的完整性。

【讨论】:

    猜你喜欢
    • 2011-05-16
    • 1970-01-01
    • 2017-04-21
    • 2014-04-26
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 2022-01-07
    • 2016-01-07
    相关资源
    最近更新 更多