在字符向量中替换 "

Replace " within a character vector

我在包含 " 字符的字符列中有数据。例如:

258
"6,962.30"
96

我正在尝试清理此列以使其成为数字。

命令:

df$Column <-sub(' .*"','',df$Column)

不工作。我该如何解决这个问题?

您可以使用 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

您只需替换逗号即可。

as.numeric(gsub(",", "", df$Column))
# [1]  258.0 6962.3   96.0

我会用 sub 和字符 class:

x <- c(258, '"6,962.30"', 96)
output <- as.numeric(gsub("[^0-9.]+", "", x))
output

[1]  258.0 6962.3   96.0

另一种基础 R 方法:

as.numeric(gsub('\"|,','',v))
[1]  258.0 6962.3   96.0