簡體   English   中英

R 如何在 R 中有效地將整列的數據類型從 char 更改為 numeric/double

[英]R How to effectively change datatype of an entire column from char to numeric/double in R

我嘗試了幾種方法將我的數據集的某些選定列從 chr 更改為 num,但是 2 列未能更改,而其余 14 列有效更改。 查看數據集,我注意到兩列中的一行在圖片的第 5 行具有 (2.4999999999863576E-2) 和 (1.6000000000076398E-2) 形式的指數值。

這是我嘗試過的代碼示例

animals[3:16] <- sapply(animals[3:16], as.numeric)

我發現第 12 列和第 13 列拒絕更改 bcos,它們包含指數值

我也在下面嘗試過查看動物數據集的屏幕截圖

animals <- animals %>%
  mutate(animals[3:16], as.numeric) %>%
  str()

我們可以使用lapply而不是sapply ,因為 sapply 返回一個matrix ,它只能有一個 class 即如果有任何列是字符,它可以導致character

animals[3:16] <- lapply(animals[3:16], as.numeric)

或使用dplyr ,使用across循環遍歷列

library(dplyr)
animals <- animals %>%
     mutate(across(3:16, as.numeric))

嘗試與format function 結合使用。

例如,

as.numeric("12389054328902")
"1.238905e+13"
format(as.numeric("12389054328902"), scientific = F)
"12389054328902"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM