【问题标题】:Changing data type from character to numeric将数据类型从字符更改为数字
【发布时间】:2021-12-28 18:04:44
【问题描述】:
我在 excel 中有一个名为 cds 的数据框,其中包含多个价格,如下所示:
主要问题是当我导出数据时,R 将价格视为字符,因此我无法对数据运行时间序列命令。
我已经在read_excel 函数中尝试了参数col_types,但问题在于将第一个日期列视为数字而不是应有的日期格式。
我已经尝试过as.numericcommand,但是它将洞数据框缩小为一个简单的向量。
我该如何解决这个问题?
【问题讨论】:
标签:
r
database
dataframe
struct
【解决方案1】:
这是一个不需要额外包的解决方案,因为它只使用“基本 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(list apply),因为 data.frame 本质上是一个列列表。
作为替代方案,即使没有 dplyr,我们也可以使用 type.convert(由 @TarJae 建议):
df <- type.convert(df, as.is=TRUE)
【解决方案2】:
您可以为此使用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))
【解决方案3】:
试试type.convert():
library(dplyr)
result <- cds %>%
type.convert(as.is = TRUE)
result