1

私はRに非常に慣れておらず、経験豊富なプログラマーではないので、私の質問が素人っぽく聞こえる場合はご容赦ください。つまり、ベクトル内の整数以外の文字を識別し、見つかった文字に対して「エラー」という出力メッセージを含むオブジェクトを作成したいと思います。

これが私が使っているコードです:

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

私はこれでいたるところにいて、私のリーグから少し外れているかもしれないことを理解しています。誰かがこれを手伝ってくれることを願っています。

4

1 に答える 1

0

とを使用することをお勧めしifelseます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 に答える