How do I create a new variable that tells me if the crime rate increased/decreased between 2010 and 2011?

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:

a<-1:5 
b<-5:1
df<-data.frame(a,b)

df%>%mutate(c=ifelse(a==b,0,ifelse(a>b,1,2)))

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
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.