如何将因子列更改为数字列

问题描述 投票:0回答:1

我有一个数据框,其类列为factor,我需要更改为数字。

head(IBOV)
          Date      Price       Open       High        Low  Vol. Change..
1 Oct 18, 2019 104,784.74 105,011.71 105,464.25 104,524.97 2.84M   -0.22%
2 Oct 17, 2019 105,015.77 105,388.63 105,891.19 104,826.61 4.19M   -0.39%
3 Oct 16, 2019 105,422.80 104,485.87 105,462.07 103,521.08 4.51M    0.89%
4 Oct 15, 2019 104,489.56 104,298.53 105,047.62 104,052.48 4.09M    0.18%
5 Oct 14, 2019 104,301.58 103,833.59 104,304.85 103,438.47 2.99M    0.45%
6 Oct 11, 2019 103,831.92 101,818.60 104,380.89 101,818.60 4.35M    1.98%

我尝试使用此代码将Cloumn 2更改为5:

IBOV[ ,2:5] <- as.numeric(gsub(",", "", IBOV[ ,2:5]))

但是R用NA填充所有值,给我此消息:

IBOV[ ,2:5] <- as.numeric(gsub(",", "", IBOV[ ,2:5]))
Warning message:
NAs introduced by coercion

有人可以帮我,我在做什么错?

r numeric factors
1个回答
0
投票

您需要先更改为character

IBOV[ ,2:5] <- as.numeric(as.character(gsub(",", "", IBOV[ ,2:5])))
© www.soinside.com 2019 - 2024. All rights reserved.