おそらく%in%演算子を使用して、値のリストを参照するときにgrepl引数を使用することは可能ですか? 以下のデータを取得したいのですが、動物名に「犬」または「猫」が含まれている場合、特定の値を返したいと考えています。「犬」または「猫」がない場合は、「破棄」を返したいです。
data <- data.frame(animal = sample(c("cat","dog","bird", 'doggy','kittycat'), 50, replace = T))
ここで、たとえば「cat」と「dog」などの値を厳密に一致させることでこれを行う場合、次のアプローチを使用できます。
matches <- c("cat","dog")
data$keep <- ifelse(data$animal %in% matches, "Keep", "Discard")
ただし、grep または grep を使用すると、リストの最初の引数のみが参照されます。
data$keep <- ifelse(grepl(matches, data$animal), "Keep","Discard")
戻り値
Warning message:
In grepl(matches, data$animal) :
argument 'pattern' has length > 1 and only the first element will be used
注、検索でこのスレッドを見ましたが、これは機能していないようです: grep using a character vector with multiple patterns