I don’t know how to conditionally create this new variable without resorting to some kind of terrible for loop. Help me!
The data is roughly as follows:
| | 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" |
< /p>
> 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 returns a logical vector, which can be assigned to anything , Such as DF $actor_type.
Break that appart:
! grepl(‘mutiny of’,df $actor) and grepl(‘military force’,df $actor) meet your first two requirements. apply(df,1,function(x)grepl(x [2],x [ 1])) line by line, greps is the country in the actor.
I have a variable actor, which is a string containing such things as “Guinea-Bissau military force (1989-1992)” and a large number of other different values that are quite complex. I have been using grep() to find character patterns that match different types of actors. For example, when the actor contains “military power”, it does not contain When “mutiny of”, I want to encode the new variable actor_type as 1, and the string variable country is also included in the variable actor.
I don’t know how to create this new variable conditionally. Don’t resort to some kind of terrible for loop. Help me!
The data is roughly as follows:
| | 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" |
If your data is located in data.frame df:
> 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 returns a logical vector, which can be assigned to anything, such as DF $actor_type.
Break that appart:
! grepl(‘mutiny of’,df $actor) and grepl(‘military force’,df $actor) meet your first two requirements. apply(df,1,function(x)grepl(x [2],x [ 1))) line by line, greps is the country in the actor.