4

我有一个变量actor,它是一个字符串,包含类似的值"military forces of guinea-bissau (1989-1992)"和大量其他相当复杂的不同值。我一直在使用grep()来寻找匹配不同类型演员的角色模式。例如,我想将一个新变量编码为何actor_type时包含,不包含,并且字符串变量也包含在变量中。1actor"military forces of""mutiny of"countryactor

我不知道如何有条件地创建这个新变量而不诉诸某种可怕的 for 循环。帮我!

数据大致如下:

|   | actor                                              | country         |
|---+----------------------------------------------------+-----------------|
| 1 | "military forces of guinea-bissau"                 | "guinea-bissau" |
| 2 | "mutiny of military forces of guinea-bissau"       | "guinea-bissau" |
| 3 | "unidentified armed group (guinea-bissau)"         | "guinea-bissau" |
| 4 | "mfdc: movement of democratic forces of casamance" | "guinea-bissau" |
4

1 回答 1

5

如果您的数据在data.framedf 中:

> ifelse(!grepl('mutiny of' , df$actor) & grepl('military forces of',df$actor) & apply(df,1,function(x) grepl(x[2],x[1])),1,0)
[1] 1 0 0 0

grepl返回一个逻辑向量,它可以分配给任何东西,例如df$actor_type.

打破那个装置:

!grepl('mutiny of', df$actor)grepl('military forces of', df$actor)满足您的前两个要求。最后一块,apply(df,1,function(x) grepl(x[2],x[1]))逐行和greps演员的国家。

于 2012-02-04T20:53:21.360 回答