如何在R中使用regex函数来标识元素,并在元素存在时创建输出消息
我对R很陌生,不是一个有经验的程序员,所以如果我的问题听起来很业余,请原谅我。简言之,我想识别向量中除整数以外的任何字符,并为找到的任何字符创建一个输出消息为“error”的对象 以下是我正在使用的代码:如何在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
##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
。你不必摆弄正则表达式。