Skip to content

Instantly share code, notes, and snippets.

@mutlusun
mutlusun / char_to_number.R
Created November 16, 2020 08:28
Convert a character vector to a numeric or integer vector in R. This function converts "," to "." to take "," as a decimal separator into account. In addition, a warning is printed showing non-convertable characters.
char_to_number <- function(x) {
# replace , with point
ret <- gsub(",", ".", x, fixed = TRUE)
# check for values that cannot be converted
na_start <- is.na(ret)
na_conversion <- is.na(suppressWarnings(as.numeric(ret)))
na_conversion <- na_conversion & !na_start
if (any(na_conversion)) {