我有数据在字符列,包括"字符。例如:
258
"6,962.30"
96
我正在尝试清理这个列,使它成为数字。
命令:
df$Column <-sub(' .*"','',df$Column)
不工作。我该如何解决这个问题?
我将使用sub
与字符类:
x <- c(258, '"6,962.30"', 96)
output <- as.numeric(gsub("[^0-9.]+", "", x))
output
[1] 258.0 6962.3 96.0
您可以使用readr::parse_number
df$Column <- readr::parse_number(df$Column)
例如,
x <- c(258, '"6,962.30"', 96)
readr::parse_number(x)
#[1] 258.0 6962.3 96.0
另一种base R方法:
as.numeric(gsub('\"|,','',v))
[1] 258.0 6962.3 96.0
你只需要替换逗号。
as.numeric(gsub(",", "", df$Column))
# [1] 258.0 6962.3 96.0