简体   繁体   中英

Convert character to numeric in xts object

My desire is to convert to numeric all numbers in the following xts object.

Morover, if it was possible, substitute NA with the previous number in the same column

library(xts)
x <- structure(c("1176.67", "1175.37", "1196.10", "1182.90", "1200.30", 
"1183.20", "170.0674", "170.0586", NA, "170.1376", "170.1651", 
"170.1844", "252.10", "252.07", "252.07", "252.23", "252.34", 
"252.40", "616.09", "618.49", "620.44", "624.61", "626.66", "627.92", 
"1.44730", "1.44430", NA, "1.43710", "1.44730", "1.44120", "5238.815", 
"5238.458", "5256.423", "5261.352", "5235.514", "5182.277", "5669.918", 
"5673.797", "5668.293", "5677.272", "5613.539", "5608.027", "399.106", 
"398.800", "399.411", "402.521", "400.797", "401.521"), class = c("xts", 
"zoo"), .indexCLASS = c("POSIXct", "POSIXt"), tclass = c("POSIXct", 
"POSIXt"), .indexTZ = "GMT", tzone = "GMT", index = structure(c(1419292800, 
1419379200, 1419552000, 1419811200, 1419897600, 1419984000),
tzone = "GMT", tclass = c("POSIXct", "POSIXt")), .Dim = c(6L, 8L),
.Dimnames = list(NULL, c("GC1 COMDTY", "IBOXXMJA", "LT01TRUU",
"LT11TRUU", "MEDLCCU", "NDDLUS", "NDDUE15", "NDUEEGF")))

You can set the storage.mode to numeric.

storage.mode(x) <- "numeric"

But I encourage you to look for the root cause/source of your data being cast as character in the first place. Setting the storage.mode to numeric is potentially destructive if some of the values in your object can't be represented as numeric (R will throw a warning if any value cannot be converted).

After converting to numeric, you can use na.locf to fill in the missing values with the previous value.

x <- na.locf(x)

你可以试试这个:

x1 <- apply(x,2,as.numeric)

The link below provides a simple solution using

storage.mode(data) <- "numeric"

xts convert data from chr to numeric

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