lundi 16 avril 2018

Create new variables based on responses in existing variables that start with the word "rank"

I have a dataset which looks like this:

name currentrank rank10_desired1 rank10_desired2 rank10_desired3 rank11_desired1
  a      10         Yes              No                No            No
  b      10         No               Yes              Yes            No
  c      11         No               No                No            No

Basically, it contains information on the current ranks of participants, as well as the rank(s) they desire to have in the future. For example, participant "a" who currently is rank 10, desires to have rank 1 in the future, but not rank 2 or 3.

What I want to do is create a set of variables called desiredrank1, desiredrank2, desiredrank3, and fill them with 1 if rankX_desiredX equals to "Yes".

An (inefficient) R code would look like this:

`data$desiredrank1 <- ifelse(rank10_desired1=="Yes",1,0)
data$desiredrank1 <- ifelse(rank11_desired1=="Yes",1,0)
data$desiredrank1 <- ifelse(rank12_desired1=="Yes",1,0)
data$desiredrank1 <- ifelse(rank13_desired1=="Yes",1,0)
`

and so on.

Is there any way I can loop this easily, and make it much more efficient? Basically, if rank<whatever>_desiredX="Yes", then fill desiredrankX=1.

Thanks so much in advance!!

Aucun commentaire:

Enregistrer un commentaire