首页 > 解决方案 > 应用 as.numeric 后,矩阵列仍在“字符”类中

问题描述

library(tidyquant)
library(tidyr)
prices_hwpj <- tq_get(c("APPL","MSFT"),
                 from = "2015-01-01",
                 to = "2020-01-01",
                 get = "stock.prices",
               )
prices_hwpj <- as.matrix(prices_hwpj)
prices_hwpj <- as.matrix(prices_hwpj[,c(1,2,8)])
prices_hwpj[,3] <- as.numeric(prices_hwpj[,3])

typeof(prices_hwpj[1,3])
class(prices_hwpj[1,3])

数据在转换为矩阵之前是一个小标题。所有的元素都是性格。

我试图将第三列从字符转换为数字。但是上面的代码不起作用。类/类型的结果仍然是字符。这是为什么?

标签: rdataframetibble

解决方案


prices_hwpj <- tq_get(c("APPL","MSFT"),
                      from = "2015-01-01",
                      to = "2020-01-01",
                      get = "stock.prices",
)

prices_hwpj <- as.matrix(prices_hwpj)
prices_hwpj <- as.matrix(prices_hwpj[,c(1,2,3,8)])
prices_hwpj_value_in_a_matrix <- matrix(nrow = length(prices_hwpj[,3]), ncol =4)
prices_hwpj_value_in_a_matrix[,3]<- as.numeric(prices_hwpj[,3])
typeof(prices_hwpj_value_in_a_matrix)
class(prices_hwpj_value_in_a_matrix)
prices_hwpj_have_to_be_same_lenght <- rbind(prices_hwpj,prices_hwpj_value_in_a_matrix)
typeof(prices_hwpj_have_to_be_same_lenght)
class(prices_hwpj_have_to_be_same_lenght)

矩阵必须与 的长度相同rbind,类型double是浮点数,所以我所做的是创建一个空矩阵,其最终结果的列长度相同,行数与 prices_hwpj.


推荐阅读