gpt4 book ai didi

r - 在 xts 对象中将字符转换为数字

转载 作者:行者123 更新时间:2023-12-03 23:23:35 25 4
gpt4 key购买 nike

我的愿望是将以下 xts 对象中的所有数字转换为数字。

Morover,如果可能的话,用同一列中的前一个数字替换 NA

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")))

最佳答案

您可以设置 storage.mode到数字。

storage.mode(x) <- "numeric"

但我鼓励您首先寻找数据被转换为角色的根本原因/来源。设置 storage.mode如果对象中的某些值不能表示为数字,则转为数字可能具有破坏性(如果任何值无法转换,R 将发出警告)。

转换为数字后,可以使用 na.locf用以前的值填充缺失值。
x <- na.locf(x)

关于r - 在 xts 对象中将字符转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28135210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com