0

I bought a book so I could practice R, and this is a question I'm having a hard time with. The data concerns assassinations on leaders.

I first create an array object to represent the levels of leaders$result.

levels <- levels(leaders$result)

When calling levels, this is the output:

[1] "dies between a day and a week"              
[2] "dies between a week and a month"            
[3] "dies within a day after the attack"         
[4] "dies, timing unknown"                       
[5] "hospitalization but no permanent disability"
[6] "not wounded"                                
[7] "plot stopped"                               
[8] "survives but wounded severely"              
[9] "survives, whether wounded unknown"          
[10] "wounded lightly"

Then I am asked to use indexing of the array object, 'levels', to create a binary variable that is equal to 1 if a leader dies, and 0 if they do not. I'm encouraged to use an if else statement.

success <- ifelse(levels==levels[c(1:4)],1,0)

The code above wont work for me. I want to be able to give any death results either a 1 or 0, using indexing. Does anyone have any tips?

After this, I am asked to store the new variable as part of the original data frame, so if I was to access this, I would be able to calculate successful attempts versus non-successful attempts (in results). How would I do this?

alistaire
  • 42,459
  • 4
  • 77
  • 117
  • 1
    ``help(`%in%`)`` – Eric Watt Sep 14 '17 at 18:45
  • Alright, I have fixed that and it worked. Now I am looking to store it as part of the original data frame, how would I do that? – Matthew Braner Sep 14 '17 at 19:15
  • Storing the levels in a variable called `levels` is a bad idea, as what gets returned will be dependent on whether there are parentheses after it, and there are a few cases in R where you won't want them even if you're referring to the function. – alistaire Sep 14 '17 at 19:19
  • 1
    Towards your broader intent, a quick way would be to use regex: `leaders$dies <- grepl('dies', leaders$result)`. To fix what you've got, `leaders$dies <- leaders$result %in% levels(leaders$result)[1:4]`. Wrap in `as.integer` if you like. – alistaire Sep 14 '17 at 19:21
  • To get an actual answer, see [how to make a reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#5963610) – alistaire Sep 14 '17 at 19:22

0 Answers0