简体   繁体   中英

xts convert data from chr to numeric

I have an xts object table2 but my datas stored in it are in chr, How can I change the to numeric? I tried with as.numeric but it drop my xts format.

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

You can use coredata or storage.mode to change the underlying type of data.

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

Note that your xts object is likely character because there are non-numeric values in the file you imported. So you should expect a warning about some values being converted to NA . And you should check the integrity of your source data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM