不正确地将chr转换为R中的数字变量

时间:2019-01-27 13:49:31

标签: r dataframe dplyr

我有这些数据

   X    json_data.time.updated json_data.time.updatedISO  json_data.time.updateduk code       rate          description
1  1 Jan 19, 2019 15:18:00 UTC 2019-01-19T15:18:00+00:00 Jan 19, 2019 at 15:18 GMT  USD 3,735.7750 United States Dollar
2  1 Jan 19, 2019 15:19:00 UTC 2019-01-19T15:19:00+00:00 Jan 19, 2019 at 15:19 GMT  USD 3,735.9150 United States Dollar
3  1 Jan 19, 2019 15:51:00 UTC 2019-01-19T15:51:00+00:00 Jan 19, 2019 at 15:51 GMT  USD 3,736.9100 United States Dollar
4  1 Jan 19, 2019 15:52:00 UTC 2019-01-19T15:52:00+00:00 Jan 19, 2019 at 15:52 GMT  USD 3,735.3200 United States Dollar
5  1 Jan 19, 2019 15:54:00 UTC 2019-01-19T15:54:00+00:00 Jan 19, 2019 at 15:54 GMT  USD 3,736.7717 United States Dollar
6  1 Jan 19, 2019 15:55:00 UTC 2019-01-19T15:55:00+00:00 Jan 19, 2019 at 15:55 GMT  USD 3,736.0750 United States Dollar
7  1 Jan 19, 2019 15:57:00 UTC 2019-01-19T15:57:00+00:00 Jan 19, 2019 at 15:57 GMT  USD 3,734.9600 United States Dollar
8  1 Jan 19, 2019 15:58:00 UTC 2019-01-19T15:58:00+00:00 Jan 19, 2019 at 15:58 GMT  USD 3,734.9117 United States Dollar
9  1 Jan 19, 2019 16:00:00 UTC 2019-01-19T16:00:00+00:00 Jan 19, 2019 at 16:00 GMT  USD 3,734.2833 United States Dollar
10 1 Jan 19, 2019 16:01:00 UTC 2019-01-19T16:01:00+00:00 Jan 19, 2019 at 16:01 GMT  USD 3,734.4950 United States Dollar
   rate_float
1    3735.775
2    3735.915
3     3736.91
4     3735.32
5   3736.7717
6    3736.075
7     3734.96
8   3734.9117
9   3734.2833
10   3734.495

我需要df$rate_float是数字变量

我这样做

df$rate_float<-as.numeric(df$rate_float)

但是结果是df$rate_float变成了有序的

1
2
3
4

丢失实际值。 如何将chr转换为num,原始值没有消失?

1 个答案:

答案 0 :(得分:1)

您尚未包含dput的数据,但是显然rate_float是一个因素而不是字符。在这种情况下,您需要

as.numeric(as.character(df$rate_float))

同时,您提供的方法类似于因子ID。