1

I am very new to R and not an experienced programmer so if my question sounds amateurish please forgive me. In short, I want to identify any characters other than integers in a vector and create an object with an output message "error" for any that are found.

Here is the code that I am working with:

##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"

I realize that I am all over the place with this and may be a little out of my league. I'm hoping someone can help me with this.

4

1 回答 1

0

我建议使用ifelseand grepl

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

但是请注意,您原来的正则表达式没有按您预期的方式工作,所以我用一个更简单的例子代替。

于 2012-09-14T21:58:06.463 回答