清理一个字符字符串并将其转换为数字
我有一个字符字符串。
abc <- "Â 267750Â"
class(abc)
"character"
我需要做什么才能去掉“ ”并将其从字符转换为数字。也许使用as.numeric会起作用,但我需要先处理掉“ ”。
我想将上述内容转换为:
abc
267750
class(abc)
"numeric"
感谢您的帮助。
清理一个字符字符串并将其转换为数字
我有一个字符字符串。
abc <- "Â 267750Â"
class(abc)
"character"
我需要做什么才能去掉“ ”并将其从字符转换为数字。也许使用as.numeric会起作用,但我需要先处理掉“ ”。
我想将上述内容转换为:
abc
267750
class(abc)
"numeric"
test <- "532.dcx3vds98"
destring <- function(x,keep="0-9.") {
return( as.numeric(gsub(paste("[^",keep,"]+",sep=""),"",x)) )
}
destring(test)
返回532.398
。
编辑
现在在taRifx
中:
library(taRifx)
test <- "532.dcx3vds98"
destring(test)
stringr
稍微缩短一下: # load library
library(stringr)
# load data
abc <- "Â 267750Â"
# extract digits
abc <- as.numeric(str_extract(abc, "[0-9]+"))
# check the result
abc
[1] 267750
class(abc)
[1] "numeric"
taRifx
中添加该功能,以便更容易使用。如果有人想到需要添加的聪明特性(或更好的函数名称),请告诉我。 - Ari B. Friedman