从字符串变量创建虚拟变量

时间:2017-03-23 09:56:01

标签: r dummy-variable

我正在尝试从现有数据集的列变量创建虚拟变量。我感兴趣的变量是这种格式的标题:

化学品 - 2015年3月31日委员会委托指令(EU)2015/863,修订欧洲议会和理事会关于限制物质清单的指令2011/65 / EU的附件II(与EEA相关的文本)< / p>

委员会实施指令(EU)2015/2392 ......

我想创建一个虚拟变量,表明Title正在实现或委托。换句话说,当'&34;'委托&#34;在我的标题变量中,这将标记为1,其他所有内容都将标记为0.

任何人都可以帮我吗?非常感谢。到目前为止,我已经使用了这段代码:

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

当我运行代码时,我得到0个匹配,即使我知道有41个匹配。

3 个答案:

答案 0 :(得分:2)

使用包str_detect()

中的stringr
library(stringr)

as.integer(str_detect(infringements$Title,"Delegated"))

答案 1 :(得分:2)

我们可以做到

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

答案 2 :(得分:1)

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))
相关问题