我有一個包含調查回復的資料框。提取數字并將它們更改為雙精度型變數的最佳方法是什么?
這是一個小示例:
a <- ("10.5", "about 30", "25 per month")
tibble(a)
我試過了
parse_double(a)
似乎我很接近。任何幫助表示贊賞
uj5u.com熱心網友回復:
我們需要 parse_number
library(readr)
parse_number(a)
[1] 10.5 30.0 25.0
不同之處在于它parse_double適用于只有數字 .作為字符的字符向量,而parse_number從還包括非數字字符的字串中提取數字部分
資料
a <- c("10.5", "about 30", "25 per month")
uj5u.com熱心網友回復:
我也知道一個解決方案(從base包中)
a <- c("10.5", "about 30", "25 per month")
as.numeric(gsub("[[:alpha:]]", "", a))
> as.numeric(gsub("[[:alpha:]]", "", a))
[1] 10.5 30.0 25.0
> end_time <- Sys.time()
> end_time - start_time
Time difference of 0.01400113 secs
> start_time <- Sys.time()
> parse_number(a)
[1] 10.5 30.0 25.0
> end_time <- Sys.time()
> end_time - start_time
Time difference of 0.1500092 secs
我的解決方案比Akrun 提供的解決方案更快。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/321982.html
下一篇:決議陳述句并為其添加括號
