我在 excel 中有一個名為cds的資料框,它包含幾個隨時間變化的價格,如下所示:

主要問題是,當我匯出資料時,R 將價格視為字符,因此我無法對資料運行時間序列命令。

我已經嘗試過函式col_types中的read_excel引數,但問題是將第一個日期列視為數字而不是日期格式。
我已經嘗試過該as.numeric命令,但是它將孔資料幀縮小為一個簡單的向量。
我該如何解決這個問題?
uj5u.com熱心網友回復:
嘗試type.convert():
library(dplyr)
result <- cds %>%
type.convert(as.is = TRUE)
result
uj5u.com熱心網友回復:
您可以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))
uj5u.com熱心網友回復:
這是一個不需要額外包的解決方案,因為它只使用“基本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 ) 因為 adata.frame本質上是一個列串列。
作為替代方案,type.convert即使沒有dplyr,我們也可以使用(如@TarJae 所建議的):
df <- type.convert(df, as.is=TRUE)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/360304.html
