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.

推荐答案

我的问题已经在 comments 中得到了回答.

  1. readline将"123"读作""123""
  2. NA没有附加任何一个类.这就是为什么我的Type判断站没有帮助发现最初的问题. 感谢安德鲁·威尔德伯格的回答!

R相关问答推荐

根据R中的另一个日期从多列中 Select 最近的日期和相应的结果

terra nearest()仅为所有`to_id`列返回NA

以更少间隔的较小表中的聚合离散频率表

在R中按行按列范围查找最大值的名称

如何基于两个条件从一列中提取行

如何根据数据帧中的值从该数据帧中提取值?

如何在使用箭头R包(箭头::OPEN_DATASSET)和dplyr谓词时编写具有整齐计算的函数?

在点图上绘制置信度或预测区间ggplot2

按组内中位数分类

`-`是否也用于数据帧,有时使用引用调用?

用多边形替换地块点

将文本批注减少到gglot的y轴上的单个值

为什么将负值向量提升到分数次方会得到NaN

名字的模糊匹配

如何将EC50值绘制在R中的剂量-react 曲线上?

Ggplot2如何找到存储在对象中的残差和拟合值?

网络抓取NBA.com

具有由向量定义的可变步长的序列

带查找数据的FCT_REORDER.帧

如何使用ggsurvfit包更改风险表中的标签名称?