将数据类型从字符更改为数字

Changing data type from character to numeric

我在 excel 中有一个名为 cds 的数据框,它包含随时间变化的几个价格,如下所示:

主要问题是当我导出数据时,R 将价格视为字符,因此我无法 运行 对数据进行时间序列命令。

我已经在 read_excel 函数中尝试了参数 col_types,但问题是将第一个日期列视为数字而不是应有的日期格式。

我已经尝试过 as.numeric 命令,但是它将孔数据框缩小为一个简单的向量。

我该如何解决这个问题?

尝试 type.convert():

library(dplyr)

result <- cds %>% 
  type.convert(as.is = TRUE)

result

您可以为此使用 dplyr::mutate

## make some fake data ##
mtcars$mpg = as.character(mtcars$mpg)
mtcars$cyl = as.character(mtcars$cyl)

## the columns we want to convert to numeric
cols = c("mpg", "cyl")

## command to mutate the cols and apply the function as.numeric to them
librar(dplyr)
mtcars %>% mutate(across(all_of(cols), as.numeric))

这里是一个不需要额外包的解决方案,因为它只使用“base R”函数:

## create a data example
df <- data.frame(
  id = letters[1:10],
  x = as.character(sample(10, 10)),
  y = as.character(runif(10))
)

## convert columns x and y
cols <- c("x", "y")
df[cols] <- lapply(df[cols], as.numeric)

它适用于 lapply列表应用),因为 data.frame 本质上是一个列列表。

作为替代方案,我们也可以使用 type.convert(正如@TarJae 所建议的),即使没有 dplyr:

df <- type.convert(df, as.is=TRUE)