R logo

R で if 構文を使うときに時々遭遇する下記エラーメッセージ。

the condition has length > 1 and only the first element will be used

例えば、下記のようなデータフレームで、

r-condition-has-length-1

"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()関数に個々の要素ではなく、ベクトルを渡した場合に発生するらしい。

 

解決方法としては、

sapply()

ifelse()

関数を使う。

例えば上記の例だと、

Dat$Region <- ifelse(str_detect(Dat$Region, "-$"), str_sub(Dat$Region, 1, -2), Dat$Region)

とすればよい。

r-condition-has-length-2
にほんブログ村 子育てブログ ワーキングマザー育児へ