在R

时间:2018-03-21 14:45:41

标签: r

我有197个关于位置的关卡,我想通过创建一个新的变量" INSIDE"来简化这个问题。当位置是建筑物/家庭/等时存储1,当位置在外面时存储0。我试过grepl()但是它给出了一个错误

data$Inside<-ifelse(grepl(data$Premise.Description,pattern = c("BUILDING","ROOM","AUTO","BALCONY","BANK","BAR","STORE","CHURCH","COLLEGE","CONDOMINIUM","CENTER","DAY CARE","SCHOOL","HOSPITAL","LIBRARY","PARLOR","OFFICE","MOSQUE","CLUB","PORCH","MALL","WAREHOUSE")),1,0)
  

警告讯息:   在grepl(crime_3yr $ Premise.Description,pattern = c(&#34; BUILDING&#34;,:     论证&#39;模式&#39;长度> 1,只使用第一个元素

我尝试过使用lapply(),但它也没有用。 我希望输出像这样:

BUILDING   1
SHOP       1
Street     0

4 个答案:

答案 0 :(得分:0)

试试这段代码:

您的data.frame:

data<-data.frame(Premise.Description= c("BUILDING 1","MY ROOM","AUTO","BALCONY","OTHER"))

解决方案:

toMatch<-c("BUILDING","ROOM","AUTO","BALCONY","BANK","BAR","STORE","CHURCH","COLLEGE","CONDOMINIUM","CENTER","DAY CARE","SCHOOL","HOSPITAL","LIBRARY","PARLOR","OFFICE","MOSQUE","CLUB","PORCH","MALL","WAREHOUSE")
data$Inside<-grepl(paste(toMatch,collapse="|"), data$Premise.Description)
data
  Premise.Description Inside
1          BUILDING 1   TRUE
2             MY ROOM   TRUE
3                AUTO   TRUE
4             BALCONY   TRUE
5               OTHER  FALSE

答案 1 :(得分:0)

您可能最好使用data.table:

library(data.table)
setDT(data)
data[
grepl(c("BUILDING","ROOM","AUTO","BALCONY","BANK","BAR","STORE","CHURCH","COLLEGE","CONDOMINIUM","CENTER","DAY CARE","SCHOOL","HOSPITAL","LIBRARY","PARLOR","OFFICE","MOSQUE","CLUB","PORCH","MALL","WAREHOUSE"), Premise),
  Inside := TRUE
]

答案 2 :(得分:0)

grepl使用正则表达式而不是选项列表,试试这个:

data$Inside<-ifelse(grepl(data$Premise.Description,pattern = "BUILDING|ROOM|AUTO|BALCONY|BANK|BAR|STORE|CHURCH|COLLEGE|CONDOMINIUM|CENTER|DAY CARE|SCHOOL|HOSPITAL|LIBRARY|PARLOR|OFFICE|MOSQUE|CLUB|PORCH|MALL|WAREHOUSE"),1,0)

答案 3 :(得分:0)

如果你想保持代码与你列出的代码类似,你需要查看正则表达式,这是grepl的模式部分所需要的。

data$Inside<-ifelse(grepl(data$Premise.Description,pattern = "BUILDING|ROOM|AUTO|BALCONY|BANK|BAR|STORE|CHURCH|COLLEGE|CONDOMINIUM|CENTER|DAY CARE|SCHOOL|HOSPITAL|LIBRARY|PARLOR|OFFICE|MOSQUE|CLUB|PORCH|MALL|WAREHOUSE"),1,0)