Zac*_*ach 4 r data-manipulation
我有一个变量actor,它是一个字符串,包含类似的值"military forces of guinea-bissau (1989-1992)"和大量其他相当复杂的值.我一直在用它grep()来寻找与不同类型的演员相匹配的角色模式.例如,我想编写一个新的变量actor_type作为1时actor包含"military forces of",不包含"mutiny of",而字符串变量country也包含在变量actor.
我不知道如何有条件地创建这个新变量而不诉诸某种类型的可怕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" |
Run Code Online (Sandbox Code Playgroud)
如果您的数据是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
Run Code Online (Sandbox Code Playgroud)
grepl返回一个逻辑向量,这可以分配给任何东西,例如df$actor_type.
打破那个appart:
!grepl('mutiny of', df$actor)并grepl('military forces of', df$actor)满足您的前两个要求.最后一块,apply(df,1,function(x) grepl(x[2],x[1]))一行一行greps,演员中的国家.