如何验证 R 中的 readLines() 输入为数字还是字符

问题描述 投票:0回答:1

我正在强制来自

readLines()
的输入,据我所知,它将接受任何输入、字符或数字,并将其捕获为数值。然后我想使用
as.numeric()
将输入转换为数值。

我想使用诸如

is.numeric()
之类的验证测试来检查用户是否使用assertthat包输入了5与字符串“五”。

但是,当我将字符向量(例如“五”)强制为

as.numeric()
时,它将产生 NA 输出。当你用
is.numeric()
测试 NA 输出时,它会产生一个 TRUE ,破坏了整个目的

如果

readLines()
将所有内容都转换为字符向量,如何验证用户输入的数值?

#both of the below produce TRUE 
  is.numeric(as.numeric("five"))
  is.numeric(as.numeric(5))
r vector type-conversion numeric
1个回答
0
投票

我相信你可以用

!is.na
来测试
as.numeric
的结果。如果未能转换为有效数值,则
as.numeric
返回
NA

!is.na(as.numeric("five"))
#> Warning: NAs introduced by coercion
#> [1] FALSE
!is.na(as.numeric("5"))
#> [1] TRUE
!is.na(as.numeric(5))
#> [1] TRUE

或者使用正则表达式

^[0-9]+$
来查看整个输入是否完全由整数组成(仅用于测试整数,不适用于测试浮点数)。

grepl("^[0-9]+$", "five")
#> [1] FALSE
grepl("^[0-9]+$", "fi55ve")
#> [1] FALSE
grepl("^[0-9]+$", "356236345")
#> [1] TRUE
grepl("^[0-9]+$", 5235)
#> [1] TRUE

创建于 2023-09-15,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.