
R で if 構文を使うときに時々遭遇する下記エラーメッセージ。
the condition has length > 1 and only the first element will be used
例えば、下記のようなデータフレームで、

"Region" 列の "Ctx-" の "-" だけ取り除きたいと思った時、普通に
sub()
や
gsub()
を使うと、途中にある "-" を変換してしまうので、下記のようにしてみた。
if(str_detect(Dat$Resion, "-$")){
str_sub(Dat$Resion, 1, -2)
} else{
Dat$Resion
}
そしたら、
the condition has length > 1 and only the first element will be used
が出現。
これは、if()関数に個々の要素ではなく、ベクトルを渡した場合に発生するらしい。
This tutorial explains how to fix the following error in R: the condition has length > 1 and only the first element will be used.
解決方法としては、
sapply()
か
ifelse()
関数を使う。
例えば上記の例だと、
Dat$Region <- ifelse(str_detect(Dat$Region, "-$"), str_sub(Dat$Region, 1, -2), Dat$Region)
とすればよい。
