Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中使用regex函数来标识元素,并在元素存在时创建输出消息_Regex_R - Fatal编程技术网

如何在R中使用regex函数来标识元素,并在元素存在时创建输出消息

如何在R中使用regex函数来标识元素,并在元素存在时创建输出消息,regex,r,Regex,R,我对R很陌生,不是一个有经验的程序员,所以如果我的问题听起来很业余,请原谅我。简言之,我想识别向量中除整数以外的任何字符,并为找到的任何字符创建一个输出消息为“error”的对象 以下是我正在使用的代码: ##create dataframe fireplaces <- data.frame(num.fireplaces <- c(0:5, "one", "two", "NA", "N/A", "zero", "none"), fireplace.exists <- c(TRU

我对R很陌生,不是一个有经验的程序员,所以如果我的问题听起来很业余,请原谅我。简言之,我想识别向量中除整数以外的任何字符,并为找到的任何字符创建一个输出消息为“error”的对象

以下是我正在使用的代码:

##create dataframe
fireplaces <- data.frame(num.fireplaces <- c(0:5, "one", "two", "NA", "N/A", "zero", "none"), fireplace.exists <- c(TRUE, TRUE,TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE))

##use grep function to identify unwanted character strings (in this case, any element that is not an integer)
fail <- grep("[^[:digit:]]", (num.fireplaces), value=TRUE)

##use gsub function to replace unwanted strings with messaging. **Problem** messaging is repeated with each character in the string
gsub("[^[:digit:]]", "Error", (num.fireplaces), ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)

## This is the error message that I would like to show as output if non-integer elements are found in the vector "num.fireplaces"
"Error"
##创建数据帧

壁炉我建议使用
ifelse
grepl

ifelse(grepl("^[0-9]+",num.fireplaces),num.fireplaces,"Error")
[1] "0"     "1"     "2"     "3"     "4"     "5"     "Error" "Error" "Error" "Error" "Error" "Error"

但是请注意,您原来的正则表达式并没有按照您预期的方式工作,因此我用一个更简单的示例替换了它。

您是否正在尝试构建一个函数?如果您使用
stopifnot
stop
会更好。此外,如果您正在尝试查看
num.fireplaces
是否为
numeric
,则您具有执行该操作的函数
is.numeric
。你不必摆弄正则表达式。