Преобразование в число

Простые типы / Строки

# To integer
str_number <- "42"
number <- as.integer(str_number)
# number = 42

# To double
str_pi <- "3.14"
pi_float <- as.numeric(str_pi)
# pi_float = 3.14

# The decimal comma is not understood
str_half <- "0,5"
half <- as.numeric(sub(",", ".", str_half,
                       fixed = TRUE))
# half = 0.5

# A decimal string to integer is cut, not rejected
cut_int <- as.integer(str_pi)
# cut_int = 3

# Wrong text: NA, not 0 and not an error
wrong <- suppressWarnings(as.numeric(str_half))
# wrong = NA

cat("number =", number, "\n")
cat("pi_float =", pi_float, "\n")
cat("half =", half, "\n")
cat("cut_int =", cut_int, "\n")
cat("wrong =", wrong, "\n")

# The NA comes with a warning
warning_text <- tryCatch(
  as.numeric(str_half),
  warning = conditionMessage)
cat("warning_text =", warning_text, "\n")
# warning_text = NAs introduced by coercion