I have two variables: CrimeRate2010 and CrimeRate2011. How do I create a new variable that codes as 0=crime rate stayed the same; 1=crime rate decreased; 2=crime rate increased.
Based on some example code I found I came up with: df$NewVariable = ifelse(df$CrimeRate2010 < df$CrimeRate2011, 2, df$DirectionCrimeRate)
But this is the error message I get: Error in ans[npos] <- rep(no, length.out = len)[npos] :
replacement has length zero
In addition: Warning message:
In rep(no, length.out = len) : 'x' is NULL so the result will be NULL
If I understand you correctly, you could use a nested ifelse to solve your problem. If you are familiar with dplyr and co. you can try something like this:
case_when has a good syntax for this sort of thing.
df %>% mutate(c=case_when(a==b ~ 0,
a>b ~ 1 ,
TRUE ~ 2))
# the last one is a catch all, true is always true so if the eary conditions fail the last one succeeds