2017-03-23 9 views
0

既存のデータセットの列変数からダミー変数を作成しようとしています。私が興味を持っている変数は、この形式のタイトルです:文字列変数からダミー変数を作成

CHEMICALS - EU議会と理事会の指令2011/65/EUへの附属書IIを改正する2015年3月31日の2015/863指令制限物質(EEA関連性を持つテキスト)のリストに関して

または

委員会の実装指令(EU)2392分の2015 ...

私はタイトルであることを示すダミー変数を作成したいです実装または委任のいずれか。言い換えれば、 "委任された"という言葉が私のタイトル変数にあるとき、これは1とラベル付けされ、それ以外は0とラベル付けされます。

誰でも助けてくれますか?非常に感謝しています。これまでのところ、私はこのコードを使用している:私は、コードを実行すると

infringements$delegated <- ifelse(infringements$Title=="Delegated", 1, 0) 
table(infringements$delegated, infringements$Title) 
summary(infringements$delegated) 

は、私は41の試合があることを知っているにもかかわらず、0の一致を得ます。

+0

を行うことができますが、最小限のデータの例を提供することはできますか? –

+0

'=='の代わりに 'stringr'パッケージの' str_detect() 'を使うことができます。' == 'はあなたの文字列が' 'Delegated ''と等しいかどうかをチェックするだけです。あなたのタイトルのパターンを検出する。 –

+2

'grepl'を使用してください。つまり、' as.integer(grepl( 'Delegated'、権利侵害$タイトル)) ' – Sotos

答えて

2

使用str_detect()パッケージからstringr

library(stringr) 

as.integer(str_detect(infringements$Title,"Delegated")) 
0
infringements = data.frame(lapply(data.frame(Title=c("CHEMICALS - Commission Delegated Directive (EU) 2015/863 of 31 March 2015 amending Annex II to Directive 2011/65/EU of the European Parliament and of the Council as regards the list of restricted substances (Text with EEA relevance)","No Text","Text3Delegated")), as.character), stringsAsFactors=FALSE) 
infringements$delegated = lapply(infringements$Title, function(x) ifelse(length(grep("Delegated", x))!=0, 1, 0)) 
2

我々は

+(grepl('Delegated', infringements$Title)) 
+2

「+」記号とは何ですか? –

+0

@AleksandrVoitovこれは、論理をバイナリに強制するハックな方法です。より良いアプローチは 'as.integer(grepl(...' – akrun