2016-06-27 15 views
0

仮説的なデータフレーム:$ DF文字列は「メッシュの文字列が含まれている場合R:1またはいくつかの可能な文字列の一致に基づいて、データフレーム内の新しい列を移入

strings  new column 
mesh   1 
foo   0 
bar   0 
tack   1 
suture  1 

は、私が「1」を含むように新しい列を希望します"、" tack "、または" sutur "のいずれかです。それ以外の場合は、同じ行にゼロが表示されます。

df$new_column <- ifelse(grepl("mesh" | "tack" | "sutur", 
    df$strings, ignore.case = T), "1", "0") 

が、このエラーました:私は、次のことを試してみました事前に

Error in "mesh" | "tack" : 
    operations are possible only for numeric, logical or complex types 

感謝を。

答えて

4

あなたはgrepに単一の文字列を使用したい:

df$new_column <- ifelse(grepl("mesh|tack|sutur", df$strings, ignore.case = T), 
         "1", "0") 

は動作しますが、以下は速くなります。

df$new_column <- +(grepl("mesh|tack|sutur", df$strings, ignore.case = T)) 

これは

+0

これはトリックです。ありがとう! – soosus

3
0と1の整数ベクトルを返します。

もご利用いただけます%in%

df$new_column <- as.integer(df$strings %in% c("mesh", "tack", "sutur")) 
+1

ありがとう!このアプローチはまた私のために働いた。 – soosus

関連する問題