I am writing a short program in R that tells the user whether their input is numeric or not.
Here is my code:
numeric_check <- function() {
input <- readline(prompt="Enter something: ")
cat("Input: ", input, "\n")
cat("Input type: ", class(input), "\n")
check <- as.numeric(input)
cat("NA or number? ", check, "\n")
cat("Type:", class(check), "\n")
if (is.na(check)) {
print("Not numeric.")
} else {
print("Numeric.")
}
}
It works fine when I input a number.
However, when I input the string, "123", the "NA or number?" checkpoint prints out "NA", while the "Type" checkpoint prints out "numeric".
I checked the portion where I suspect might be the issue:
test <- as.numeric("123")
test
这表现为
123
instead of "NA" as it does in my program above.
Why does the program print out "NA" for as.numeric("123") and when I check it individually, it prints out the numeric type 123?
If someone can point to what I have missed, I would be very grateful. Thank you.